這是(用戶)micmoo對What is the difference between class and instance methods?的迴應的後續問題。跟進:類方法和實例方法之間的區別?
如果我將變量numberOfPeople從靜態更改爲類中的局部變量,我將numberOfPeople設置爲0.我還在每次增加變量後添加了一行以顯示numberOfPeople。只是爲了避免任何混亂,我的代碼如下:
// Diffrentiating between class method and instance method
#import <Foundation/Foundation.h>
// static int numberOfPeople = 0;
@interface MNPerson : NSObject {
int age; //instance variable
int numberOfPeople;
}
+ (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
int numberOfPeople = 0;
- (id)init{
if (self = [super init]){
numberOfPeople++;
NSLog(@"Number of people = %i", numberOfPeople);
age = 0;
}
return self;
}
+ (int)population{
return numberOfPeople;
}
- (int)age{
return age;
}
@end
int main(int argc, const char *argv[])
{
@autoreleasepool {
MNPerson *micmoo = [[MNPerson alloc] init];
MNPerson *jon = [[MNPerson alloc] init];
NSLog(@"Age: %d",[micmoo age]);
NSLog(@"Number Of people: %d",[MNPerson population]);
}
}
輸出:
在初始塊。人數= 1在init塊中。人數= 1年齡:0人數:0
案例2:如果您將執行中的numberOfPeople更改爲5(說)。輸出仍然沒有意義。
非常感謝您的幫助。
您不更改類型,而是創建新變量。 – Dustin 2012-08-09 17:22:42
非常感謝達斯汀! – 2012-08-09 20:35:52