为什么在应用程序中自动释放窗口:didFinishLaunchingWithOptions:并在dealloc中释放?

jor*_*mol 2 iphone xcode autorelease ios xcode4.2

我在xcode 4.2中使用没有ARC的空模板创建了一个iphone应用程序.我目前没有使用ARC,因为我想学习引用计数的基础知识.在应用程序委托中,我有以下方法:

- (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;
 }
Run Code Online (Sandbox Code Playgroud)

为什么要window自动释放?是因为AppDelegate将来不会使用它吗?但它被分配给实例变量.还有一个window释放的dealloc方法.它为什么在已经自动释放时发布?

- (void)dealloc
{
    [_window release];
    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)

Bru*_*ues 6

windowin .h文件的属性声明为@property (nonatomic, retain) UIWindow *window;.该window有一个retain属性.因此UIWindow,window变量的setter方法保留了它.在self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];新的window alloced中+1,retainCount因为alloc和另一个+1因为windowsetter方法导致a +2 retainCount.该autorelease是降低retainCount+1.在deallocretainCount0window被释放.