property,synthesize,dynamic

280 阅读1分钟

property 、 synthesize

property做的事情。
@property (assign, nonatomic) int age;

  • 生成setter和getter方法的声明
  • 生成 @synthesize age = _age.
  • 生成setter和getter方法的实现

@synthesize

  • 默认是 @synthesize age = _age;
  • 如果 @synthesize age; 会生成成员变量age,而不是_age

dynamic

// 提醒编译器不要自动生成setter和getter的实现、不要自动生成成员变量 @dynamic age;

注意:只生成setter,getter方法的声明,成员变量也不生成。

@property (assign, nonatomic) int age;
void setAge(id self, SEL _cmd, int age)
{
    NSLog(@"age is %d", age);
}

int age(id self, SEL _cmd)
{
    return 120;
}


+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    
    if (sel == @selector(setAge:)) {
        class_addMethod(self, sel, (IMP)setAge, "v@:i");
        return YES;
    } else if (sel == @selector(age)) {
        class_addMethod(self, sel, (IMP)age, "i@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}