tags:

views:

239

answers:

3

Hi While fixing third-party code I've discovered a really brilliant idea) Guy was using 2 appDelegate objects in project xibs. I assume he thought that this would be some kind of singletone or such. But after some rethinking of that piece of code, I found that there is no technical restrictions on it. Here is my example: simple project with navController and 2 views. Each with it's viewController. When app launched, first view is on screen. When user taps button, second view is pushed to navController. For now there is appDelegate object in MainWindow.xib. Now, if you'll add just the same appDelegate object to second view's xib. Now right when second view is pushed, you can see that one more instance of appDelegate is created and destroyed (if you'll override init and dealloc methods and insert log there). Here I'm very surprised. Does it mean that only one appDelegte instance can be created? If yes, then why? appDelegate is just a NSObject subclass implementing UIApplicationDelegate protocol.

A: 

The appDelegate object created by xCode on every iphone project is the entry and exit point of an application. It does not make sence to have more than one instance of this class, if you do (besides perhaps some application settings being lost) which class does the applicaiton delegate to? Why can you only make one? Most probably this is because the class is implementing a Singleton patterns under covers so ensure only one instance of the app delegate is made, i bet that even when you try to alloc another one of these, the original app delegate is the only one kept. You can probably dig around the docs and find more info on apples site at http://developer.apple.com/iphone

Daniel
A: 

UIApplicationDelegate is a protocol and doesn't have state in itself, thus there's nothing that prevents you to have several of them. Contrast this with UIApplication that has state and provides sharedApplication singleton accessor

It should be totally possible to replace UIApplication's delegate property on the fly. I don't see much of the benefit, though.

tequilatango
A: 

I think what's happening here is that there is an instance of the AppDelegate class in the second Nib, but no other objects are retaining it. Therefore it gets created and immediately released. If you added a retained property to the view controller that connected to the AppDelegate, then it wouldn't get released immediately.

You can have multiple objects that implement the UIApplicationDelegate protocol, but it's not usually done because 90% of the behavior would be identical in all cases.

Mark Bessey