跟进:类方法和实例方法之间的区别



这是(用户)micmoo关于类和实例方法之间有什么区别的回答的后续问题?。

如果我将变量: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 在初始化块中。人数 = 1 年龄: 0 人数: 0

情况 2:如果将实现中的人员数量更改为 5(例如)。输出仍然没有意义。

提前感谢您的帮助。

您使用实例级别 numberOfPeople 隐藏全局声明的numberOfPeople。 将他们的一个名字更改为其他名称以避免此问题

最新更新