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

Objective-C - 何时使用“自我

问题描述:

这是来自 Apple iPhone 'Utility Application' 模板的未经修改的代码:

This is unmodified code from Apple's iPhone 'Utility Aplication' template:

- (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关键字:

When mainViewController is assigned to aController, the self keyword is specified:

 self.mainViewController = aController;

然而,当mainViewController的frame被设置时,self关键字就不是必需的:

However, when the mainViewController's frame is set, the self keyword is not required:

 mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;

如果我从第一个示例中删除 self 关键字,程序会崩溃并显示以下消息:

If I remove the self keyword from the first example, the program crashes with the message:

objc[1296]: FREED(id): message view sent to freed object=0x3b122d0

如果我将 self 关键字添加到第二个示例中,程序运行良好.

If I add the self keyword to the second example, the program runs fine.

谁能解释为什么在第一种情况下需要 self 而在第二种情况下不需要?我假设在这两种情况下 mainViewController 指的是同一个实例变量.

Can anyone explain why self is needed in the first case but not the second? I'm assuming that in both cases mainViewController is referring to the same instance variable.

使用 self 会导致调用类的setter"来调用此变量,而不是直接更改 ivar.

Using self causes your class' "setter" for this variable to be called, rather than changing the ivar directly.

self.mainViewController = aController;

相当于:

[self setMainViewController:aController];

另一方面:

mainViewController = aController;

只需直接更改mainViewController 实例变量,跳过可能内置于UIApplication 的setMainViewController 方法中的任何附加代码,例如释放旧对象、保留新对象、更新内部变量等.

just changes the mainViewController instance variable directly, skipping over any additional code that might be built into UIApplication's setMainViewController method, such as releasing old objects, retaining new ones, updating internal variables and so on.

在您访问框架的情况下,您仍然在调用 setter 方法:

In the case where your accessing the frame, you're still calling a setter method:

mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;

扩展为:

[[mainViewController view] setFrame:[[UIScreen mainScreen] applicationFrame]];

理想情况下,为了将来证明您的代码,您还应该在检索此值时使用 self.mainViewController(或 [self mainViewController]).一般来说,与setter"相比,类在其getter"方法中不太可能包含重要代码,但在 Cocoa Touch 的未来版本中,直接访问仍有可能会破坏某些内容.

Ideally, to future proof your code, you should also be using self.mainViewController (or [self mainViewController]) when retrieving this value too. In general, classes are much less likely to have important code in their "getter" methods than their "setters", but it's still possible that accessing directly could break something in a future version of Cocoa Touch.