objective-c实例变量

sel*_*tch 1 variables methods class objective-c instance

几年前有一个问题是re-instance vs class方法.它用以下代码说明.我理解大部分,除了为什么我需要实例变量"age"和实例方法"age"?

不会使用@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]);
Run Code Online (Sandbox Code Playgroud)

(原始代码来自@micmoo)

das*_*ght 5

实例方法age用于封装.它允许子类覆盖该方法,如果需要,提供不同的实现.例如,子类可能希望根据初始日期和当前日期计算年龄,而不是存储它.如果使用实例变量,则子类将无法覆盖age; 如果添加实例方法,则子类将能够提供新的实现.

另一个优点是你不能写age:你的班级用户可以得到age,但他们不能set.

不会使用@synthetize?创建实例变量"age"的getter和setter ?

@synthesize需要申报财产,这是从类失踪.属性对于该语言来说相对较新,这可以解释为什么它们不会在您找到的代码中使用的原因.

目前做同样事情的方法是声明一个属性而不是一个ivar和一个存取器,并@synthesize完全跳过:

@property (nonatomic, readonly) int age;
Run Code Online (Sandbox Code Playgroud)

您可以age通过分配来自类内部写入,_age自动创建的后备变量; 用户可以使用[obj age]或者obj.age语法来读取值.