Objective-C-何时使用“自我”

这是来自Apple 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在第一种情况下需要这样做,而在第二种情况下却不需要?我假设在两种情况下mainViewController都引用相同的实例变量。


呼唤远方
浏览 505回答 3
3回答

慕村225694

使用self会导致您的类的“设置者”被调用,而不是直接更改ivar。self.mainViewController = aController;等效于:[self setMainViewController:aController];另一方面:mainViewController = aController;只需mainViewController直接更改实例变量,就可以跳过UIApplication setMainViewController方法中可能内置的任何其他代码,例如释放旧对象,保留新对象,更新内部变量等。在访问框架的情况下,您仍在调用setter方法:mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;扩展为:[[mainViewController view] setFrame:[[UIScreen mainScreen] applicationFrame]];理想情况下,为了将来验证您的代码,也应该在检索此值时也使用self.mainViewController(或[self mainViewController])。通常,类在其“ getter”方法中比在其“ setters”中具有重要代码的可能性要小得多,但是直接访问仍然有可能在将来的Cocoa Touch版本中破坏某些功能。

拉风的咖菲猫

该self关键字表明您正在使用属性的getter / setter方法,而不是直接访问值。如果让您使用同步功能自动生成getter / setter,则在第一个示例中必须使用self,因为对象保留在此处,而不仅仅是指针分配的对象。

慕尼黑5688855

除了在自己的getter和setter方法内部(如果您编写自己的方法)之外,您应该始终使用self。这样,可以自动为您处理对象保留。您还可以提供自定义代码来执行诸如验证iVar之类的操作,或者保留自零的功能。除了getter和setter方法之外,几乎没有任何直接访问iVar的理由。虽然,许多人通常是出于错误或懒惰。
打开App,查看更多内容
随时随地看视频慕课网APP