2012-12-17 19 views
0

可能重複:
How does an underscore in front of a variable in a cocoa objective-c class work?
Difference between self.ivar and ivar?
Synthesized property and variable with underscore prefix: what does this mean?時使用self.propertyname和_propertyname

要在對象C使用屬性,我有兩個選擇,其中一個應我用?

choice1:self.property = xxxx;

選擇2:_property = XXX

例如:

//.h file 

@interface ViewController : UIViewController 

    @property (retain, nonatomic) NSArray *myArray; 

@end 

//.m file 

@interfaceViewController() 

@end 

@implementation ViewController 

- (void)doing { 

    _myArray = [[NSArray alloc] init]; //choice one 
    self.myArray = [[NSArray alloc] init]; //choice two 
} 
@end 
+0

@CodaFi請按照複製鏈:) –

+0

@傑克,這是他的工作。 :P – CodaFi

+0

問題不在於下劃線語法。他問的是設置變量的兩種方法之間的區別,這不是語法或慣例的問題。 –

回答

0

我知道這個問題是退出頻繁,但我無論如何都會回答。

下劃線語法訪問該備份屬性的實例變量,而點語法僅僅是輔助方法的包裝:

object.property == [object property] 
object.property = x == [object setProperty:x] 

所以,你應該用點語法或附件方法儘可能保證一切都照顧好了。例如非ARC應用程序中的垃圾收集。你必須使用實例變量來進行初始化,釋放或自定義附件方法,但這些都是特殊情況。要獲得詳細的概述,請閱讀Objective-C手冊中關於屬性的章節:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW1

2

您正在做兩件完全不同的事情。

_myVar = [[NSArray alloc] init]; 

在上面的代碼中,您直接訪問變量。

self.myVar = [[NSArray alloc] init]; 

在正在呼叫的設置方法上面的代碼,這相當於

[self setMyVar:[[NSArray alloc] init]]; 

一般的setter(吸氣劑一起)提供的內存管理和同步功能,因此是優選的,並且通常更可以安全地使用它,而不是直接訪問伊娃。

下劃線語法僅僅是一個不會混淆伊娃和財產的慣例,因爲一個典型的錯誤是弄錯了,並意外地使用myVar而不是self.myVar。使用下劃線語法試圖阻止這種不好的做法。