【问题标题】:Followup on: Difference between class methods and instance methods?跟进:类方法和实例方法之间的区别?
【发布时间】:2012-08-06 23:10:46
【问题描述】:

这是(用户)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 在初始化块中。人数 = 1 年龄:0 人数:0

案例 2:如果您将实现中的 numberOfPeople 更改为 5(比如说)。输出仍然没有意义。

提前感谢您的帮助。

【问题讨论】:

  • 您不是在更改类型,而是在创建一个新变量。

标签: objective-c class methods


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-12-11
    • 2017-02-15
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2010-11-06
    • 2012-08-13
    相关资源
    最近更新 更多