I'm using the following code many times in my app (especially to manage a NavigationController):
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
When should I release it ?
Thx for helping,
Stephane
I'm using the following code many times in my app (especially to manage a NavigationController):
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
When should I release it ?
Thx for helping,
Stephane
Don't. Never release your application delegate - it is managed automatically by the OS.
If you look in your app's main.m file, you'll see some code that initializes an instance of UIApplication
that represents your app - it is its responsibility to manage the application delegate's lifecycle, not your responsibility.
EDIT as @Goz points out, you should release
it if at some point you retain
it. However, since the application object (and therefore, by extension its delegate) is guaranteed to remain in scope for the life of the app (unless you go messing with it), it's far better to simply not do any memory management on the delegate, as this avoids the possibility of accidental over-release or other related issues.
Short answer: never ever release your application delegate.
Explanation:
It often helps me how to address mem-mgmt issues, when I check how the things are declared. Take a look how delegate
property is declared for UIApplication
:
@property(nonatomic,assign) id<UIApplicationDelegate> delegate;
As you can see, it is assigned property meaning all mem-mgmt done here is just assigning pointers for an instance variable. It means calling release
on your application delegate will result in -dealloc
method being executed for your MyAppDelegate
. Go and try this in debugger and you'll see that your application will receive EXC_BAD_ACCESS - i.e. it will crash.
EDIT: However, as Goz suggests, you can call retain
and then release
. But in the first place, it doesn't make sense to do this retain/release
thing on app delegate.