幾年前,有一個問題涉及實例與類方法。用下面的代碼說明了它。我大部分都明白,除了爲什麼我需要實例變量「年齡」和實例方法「年齡」?objective-c實例變量
不會使用@synthetize創建變量「age」的getter和setter嗎?
Static int numberOfPeople = 0;
@interface MNPerson : NSObject {
int age; //instance variable
}
+ (int)population; //class method. Returns how many people have been made.
- (id)init; //instance. Constructs object, increments numberOfPeople by one.
- (int)age; //instance. returns the person age
@end
@implementation MNPerson
- (id)init{
if (self = [super init]){
numberOfPeople++;
age = 0;
}
return self;
}
+ (int)population{
return numberOfPeople;
}
- (int)age{
return age;
}
@end
main.m:
MNPerson *micmoo = [[MNPerson alloc] init];
MNPerson *jon = [[MNPerson alloc] init];
NSLog(@"Age: %d",[micmoo age]);
NSLog(@"%Number Of people: %d",[MNPerson population]);
(從@micmoo原始代碼)
「__不要使用@synthetize創建實例變量」age「的getter和setter?__」發佈的代碼不使用屬性。這段代碼中沒有'@ property'或'@ synthesize'。 – rmaddy 2013-02-17 19:03:24