I haven’t done any iOS development since iOS 3, so my memory is a little hazy (though memory management was never anything I struggled with and my mind is quite clear on that).
I’m starting a new project and don’t understand why the skeleton code is structured the way it is:
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc]
initWithFrame:[[UIScreen mainScreen] bounds]]
autorelease];
// ... snip ...
}
- Why would the window object be autoreleased? I’m pretty sure it never used to be this way in older iOS versions.
- Where does
_windowcome from? Is this just another way to access[self window]?
I’d have written this as:
- (void)dealloc
{
[self.window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc]
initWithFrame:[[UIScreen mainScreen] bounds]];
// ... snip ...
}
It was always drummed into me never to release an autoreleased object, and in fact doing so usually results in a segmentation fault.
In you second example you are leaking the window object since, the
allocwill give the object a retain count of 1, the you assign it_windowvia the property which will also retain the object assigned to it.It’s true you should not release an autorelease object, but in the dealloc you are releasing the iVar for the
windowproperty. You should always release any property that is declared as either retain or strong. (although not when using ARC).The
_windowis now automatically generated as the iVar for the propertywindow.There some believes that you should not use
self.properties ininitordealloc.Thus the way I do it is:
This wil set the
_windowto nil after releasing it, making sure that if any other thread might want to use this it will be calling onnil. Which could prevent a crash but could alo create some weird behavior. This is totally up to you.You should move to ARC, which is a complier option to add release/autolease at compiletime fro you. There is no need to added these your self if you set the property correctly when using ARC.