这是(用户)micmoo对What is the difference between class and instance methods?的回复的后续问题。
如果我将变量:numberOfPeople从static更改为类中的局部变量,我将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]);
}
}
输出:
在init块中。人数= 1在init块中。人数= 1年龄:0人数:0
案例2:如果将实现中的numberOfPeople更改为5(比如说)。输出仍然没有意义。
提前感谢您的帮助。
答案 0 :(得分:2)
您正在隐藏具有实例级numberOfPeople
的全局声明的numberOfPeople
。将其中一个名称更改为其他名称以避免此问题