我有幾個簡單的問題,以確保我在我的應用程序中使用屬性。我在網上閱讀了很多內容,但目前還不清楚。非常感謝您的幫助或建議。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
對於最後一個問題: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
太棒了,自從那篇文章有幫助以後,我就把它拿出來了。 – Vikings 2012-03-11 17:34:45
[Synthesized屬性和變量與下劃線前綴:這是什麼意思?]可能重複(http://stackoverflow.com/questions/6049269/synthesized-property-and-variable-with-underscore-prefix-what-does-這意味着) – 2012-03-11 18:54:33