Runtime(動態添加屬性)學習

添加屬性的本質就是將一個屬性與一個對象關聯起來(指針)。

Runtime大多是對系統類進行操作

Demo鏈接

//ViewController.m

#import "ViewController.h"
#import "NSObject+Property.h"//動態添加屬性的分類

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //爲object對象動態添加一個prop屬性
    NSObject *object = [[NSObject alloc] init];
    object.prop      = @"prop";
    NSLog(@"%@",object.prop);
}
//NSObject+Property.h

@interface NSObject (Property)

//在類別中不能添加屬性,使用@property會自動生成get、set方法聲明,不生成實現,不生成屬性
@property NSString *prop;

@end
//NSObject+Property.m

#import "NSObject+Property.h"
#import <objc/message.h>//引入Runtime

@implementation NSObject (Property)

- (void)setProp:(NSString *)prop
{
    /**
     * 通過Runtime動態添加屬性

     * object 給哪個對象添加屬性
     * key    屬性名稱
     * value  屬性值
     * policy 保存策略
     */
    objc_setAssociatedObject(self, @"prop", prop, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSString *)prop{
    return objc_getAssociatedObject(self, @"prop");
}

@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章