2012-03-11 40 views
3

我有幾個簡單的問題,以確保我在我的應用程序中使用屬性。我在網上閱讀了很多內容,但目前還不清楚。非常感謝您的幫助或建議。iPhone的屬性

(1)我不太確定該陳述是否有效,爲什麼需要。

@synthesize personName = _personName; 

爲什麼你需要_personName變量?這樣做有什麼好處,而不僅僅是創建一個屬性併合成變量personName。

@property (nonatomic, retain) NSString *personName; 

(2)在我的應用程序應該訪問屬性變量self.personName或使用_personName變量。我相信self.personName是正確的,那麼爲什麼_personName即使在那裏? (3)另外我有點困惑,我應該在dealloc()中釋放哪個變量,以及哪個變量應該在viewDidLoad()中設置爲nil。我也不知道是否應該對didReceiveMemoryWarning()方法進行任何更改。

@interface ViewController : UIViewController 
{ 
    NSString *_personName; 
} 

@property (nonatomic, retain) NSString *personName; 

@end 



@implementation ViewController 

@synthesize personName = _personName; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.personName = [[NSString alloc] initWithString:@"John Doe"]; 

    NSLog(@"Name = %@", self.personName); 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
} 

- (void)dealloc 
{ 
    [super dealloc]; 
} 

@end 
+0

對於最後一個問題:http://stackoverflow.com/questions/9276136/what-is-the-need-of-assigning-nil-after-releasing-an-object?answertab=active#tab -top – Saphrosit 2012-03-11 17:32:21

+0

太棒了,自從那篇文章有幫助以後,我就把它拿出來了。 – Vikings 2012-03-11 17:34:45

+1

[Synthesized屬性和變量與下劃線前綴:這是什麼意思?]可能重複(http://stackoverflow.com/questions/6049269/synthesized-property-and-variable-with-underscore-prefix-what-does-這意味着) – 2012-03-11 18:54:33

回答

5
@synthesize personName = _personName; 
  1. 這條語句創建了personName屬性的存取方法。您已指定訪問者應使用名爲_personName的實例變量。如果您剛剛擁有@synthesize personName;,則訪問器將使用personName作爲實例變量。

  2. 你通常應該使用存取方法,如self.personNamesomePerson.personNamesomePerson.personName = @"Joe";。如果你不關心備份personName財產的伊娃的名稱,則無需指定它。

  3. 使用-viewDidLoad中的訪問器,如:self.personName = nil;。與-didReceiveMemoryWarning:相同。是否使用伊娃或-dealloc中的財產是有爭議的,並且在某種程度上與品味有關。使用-dealloc中的屬性訪問器的主要關注點是,如果您的類被子類化並且訪問器被覆蓋,它可能會導致問題。通常情況下,你不需要擔心,因爲你知道你的班級不會被分類。

  4. 發佈伊娃後設置爲零也是有爭議的。許多人認爲這樣做很好,其他人覺得這是浪費時間。用你最好的判斷力。這當然不是必需的,而是某些人認爲是良好的家務問題。

+0

我仍然有點_conf在_personName,它似乎是不必要的,但我看到一些很多的例子,包括蘋果的例子。 – Vikings 2012-03-11 17:45:47

+0

另外,我是否應該在dealloc中釋放_personName?或self.personName和_personName? – Vikings 2012-03-11 17:48:43

+0

@ Vikings1201使用下劃線可以更容易地直觀地發現直接訪問ivar的那些位置(幾乎所有情況下都應該在自定義訪問器方法中) – 2012-03-11 17:58:25