Joe*_*Joe 49 iphone cocoa-touch objective-c
这是来自Apple的iPhone"Utility Aplication"模板的未经修改的代码:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
当mainViewController
被分配到aController
时,self
被指定的关键字:
self.mainViewController = aController;
Run Code Online (Sandbox Code Playgroud)
但是,mainViewController
设置框架时,self
不需要关键字:
mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;
Run Code Online (Sandbox Code Playgroud)
如果我self
从第一个示例中删除关键字,程序将崩溃并显示以下消息:
objc[1296]: FREED(id): message view sent to freed object=0x3b122d0
Run Code Online (Sandbox Code Playgroud)
如果我将self
关键字添加到第二个示例,程序运行正常.
任何人都可以解释为什么self
在第一种情况下需要而不是第二种情况?我假设在两种情况下mainViewController
都引用相同的实例变量.
Tob*_*hen 49
使用self会导致调用此变量的类"setter",而不是直接更改ivar.
self.mainViewController = aController;
Run Code Online (Sandbox Code Playgroud)
相当于:
[self setMainViewController:aController];
Run Code Online (Sandbox Code Playgroud)
另一方面:
mainViewController = aController;
Run Code Online (Sandbox Code Playgroud)
只是mainViewController
直接更改实例变量,跳过可能构建到UIApplication setMainViewController
方法中的任何其他代码,例如释放旧对象,保留新对象,更新内部变量等等.
在您访问框架的情况下,您仍然在调用setter方法:
mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;
Run Code Online (Sandbox Code Playgroud)
扩展为:
[[mainViewController view] setFrame:[[UIScreen mainScreen] applicationFrame]];
Run Code Online (Sandbox Code Playgroud)
理想情况下,为了将来验证您的代码,您也应该在检索此值时使用self.mainViewController
(或[self mainViewController]
).一般来说,类在他们的"getter"方法中拥有重要代码的可能性要小于"setter",但是直接访问仍然可能会在未来版本的Cocoa Touch中破坏某些东西.
Rus*_*sso 11
该self
关键字表明您正在使用属性的getter/setter方法,而不是直接访问值.如果您使用同步自动生成getter/setter,则必须在第一个示例中使用self,因为该对象保留在那里而不是简单地指针指定.
归档时间: |
|
查看次数: |
22177 次 |
最近记录: |