美文网首页
Runtime为Category添加属性

Runtime为Category添加属性

作者: 与时间共舞 | 来源:发表于2018-04-17 22:38 被阅读0次

1.创建Person类

#import <Foundation/Foundation.h>

@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 <objc/runtime.h>

@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添加属性

      本文链接:https://www.haomeiwen.com/subject/dqhmkftx.html