这是苹果iPhone"实用应用程序"模板中未经修改的代码:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
MainViewController *aController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
self.mainViewController = aController;
[aController release];
mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;
[window addSubview:[mainViewController view]];
[window makeKeyAndVisible];
}
将mainViewController
指定给aController
时,将指定self
关键字:
self.mainViewController = aController;
但是,当设置mainViewController
的帧时,不需要self
关键字:
mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;
如果我从第一个示例中删除self
关键字,程序将崩溃,并显示以下消息:
objc[1296]: FREED(id): message view sent to freed object=0x3b122d0
如果我在第二个示例中添加self
关键字,程序运行良好.
有人能解释为什么第一种情况下需要self
而第二种情况下不需要self
吗?我假设在这两种情况下,mainViewController
都引用同一个实例变量.