我很難理解爲什麼我需要聲明實例變量。讓我解釋一下我的意思..Objective C的實例變量,爲什麼我應該聲明它們?
例如..
@interface LearningViewController : UIViewController {
UILabel *myText; // <--- Instance Variables
}
@property (nonatomic,retain) IBOutlet UILabel *myText;
-(IBAction)method:(id)sender;
@end
這也可以作爲做
@interface LearningViewController : UIViewController {
//instance variables go here, but are not declared, I just leave this field blank
}
@property (nonatomic,retain) IBOutlet UILabel *myText;
-(IBAction)method:(id)sender;
@end
,你可以看到。在後者的例子中,我只建造了setter/getter爲UILabel * myText
但在前者中我也聲明瞭實例變量。
雙方最終在年底工作
@implementation LearningViewController
@synthesize myText;
-(IBAction)method:(id)sender {
[myText setText:@"hey"];
//or
NSString *myObject = [[NSString alloc]initWithString:@"hey"];
[myText setText:myObject];
}
現在這兩件事產生相同的結果。所以我的問題是,爲什麼?這樣做的好處是什麼? 我爲什麼要建立和反對
NSString *myObject = [[NSString alloc]initWithString:@"hey"];
myText.text = myObject;
時,我可以做
[myText setText:@"hey"];
在此先感謝。
謝謝賈利亞編輯我的帖子,我是相當新的在這裏提出問題(這是我的第一個問題),並感謝Williham爲了那個快速的回答。 – Andy
iOS使用現代運行時,所以在iOS中依靠合成的ivars是很好的。它曾經是iOS模擬器使用舊運行時的情況,因此如果您使用模擬器,則不能使用合成的ivars,但現在不再是這種情況。 – Caleb
@Caleb:確實;答案更新以反映這一事實。 –