I have created an iphone application using the empty template without ARC in xcode 4.2. I'm not currently using ARC because I want to learn the basics of reference counting. In the application delegate I have the following method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Why is window
autoreleased? Is it because AppDelegate won't be using it in the future? But it is being assigned to a instance variable. There is also a dealloc method where window
is released. Why is it released when it is already autoreleased?
- (void)dealloc
{
[_window release];
[super dealloc];
}
The property of the window
in .h
file is declared as @property (nonatomic, retain) UIWindow *window;
. The window
has a retain
property. So the UIWindow
is retained by the setter method of the window
variable.
In the line self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
the new window
alloc
ed has +1
in retainCount
because of the alloc
and another +1
because of the window
setter method resulting in a +2
retainCount
. The autorelease
is to decrease the retainCount
back to +1
. In the dealloc
the retainCount
goes to 0
and the window
is deallocated.