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
windowin.hfile is declared as@property (nonatomic, retain) UIWindow *window;. Thewindowhas aretainproperty. So theUIWindowis retained by the setter method of thewindowvariable.In the line
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];the newwindowalloced has+1inretainCountbecause of theallocand another+1because of thewindowsetter method resulting in a+2retainCount. Theautoreleaseis to decrease theretainCountback to+1. In thedealloctheretainCountgoes to0and thewindowis deallocated.