Objective-C - 何时使用“self”

Objective-C  - 何时使用“self”

问题描述:

这是Apple的iPhone'Utility Aplication'模板的未修改代码:

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 设置,不需要 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] )。一般来说,类在getter方法中比setter更不可能有重要的代码,但是在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.