Runtime为Category添加属性

1.创建Person类

#import 

@interface Person : NSObject

@property (nonatomic, copy)NSString *name;  // 名称

@end

2.创建Person的类别

#import "Person.h"

@interface Person (addProperty)

// 添加属性
@property (nonatomic, assign)NSInteger age;
@property (nonatomic, copy)NSString *stu;

@end

3.Person类别.m的实现

#import "Person+addProperty.h"
#import 

@implementation Person (addProperty)

static char ageKey = 'n';
static char stuKey = 's';

// 给age属性提供setter和getter方法
- (void)setAge:(NSInteger)age {
    NSString *s = [NSString stringWithFormat:@"%ld",(long)age];
    objc_setAssociatedObject(self, &ageKey, s, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSInteger)age {
   return [objc_getAssociatedObject(self, &ageKey) integerValue];
}

// 给stu属性提供setter和getter方法
- (void)setStu:(NSString *)stu {
    objc_setAssociatedObject(self, &stuKey, stu, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)stu {
    return objc_getAssociatedObject(self, &stuKey);
}

4.属性的使用

#import "ViewController.h"
#import "Person+addProperty.h"

- (void)viewDidLoad {
    [super viewDidLoad];
   
    // 测试分类的添加属性
    Person *p = [[Person alloc] init];
    p.name = @"张三";  // 原有的属性
    p.age = 30;       // 添加的属性
    p.stu = @"Good";  // 添加的属性
    
    NSLog(@"%@---%ld---%@",p.name,p.age,p.stu);
}

// 控制台打印结果为
text1[14973:2226652] 张三---30---Good



你可能感兴趣的:(Runtime为Category添加属性)