iOS之Runtime初应用

iOS之Runtime初应用

runtime一个强大的功能,但是可以做一些强大的事情,最近看了一点,在这里简单的用一下。

1、runtime 之获取对象属性。

代码如下:

 1 - (NSArray *)getPropertiesArray:(Class)clas {
 2 
 3     unsigned int count = 0;
 4 
 5     // 获取 xx 类的属性列表 只可以获取到本类的属性获取到父类的属性)
 6     objc_property_t *properties = class_copyPropertyList([clas class], &count);
 7     
 8     NSMutableArray *propertiesArray = [@[] mutableCopy];
 9     // 遍历所有属性
10     while (count--) {
11         
12         // 获取 count "位置" 的属性名
13         const char* propertyName = property_getName(properties[count]);
14         
15         // 把属性名称C字符串转为 OC字符串
16         NSString *strName = [NSString stringWithUTF8String:propertyName];
17         
18         NSLog(@"clas 的属性  ====== %@",strName);
19         
20         [propertiesArray addObject:strName];
21     }
22     return propertiesArray;
23 }

获取到属性以后就可做自己属性的事情了,(集合KVC)。

2、对象绑定。

代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 把 self 和 @"123" 以 @"key" 绑定起来。
    objc_setAssociatedObject(self, @"key", @"123", OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取 self 以 self 绑定的对象
    id obj = objc_getAssociatedObject(self, @"key");
    NSLog(@"%@",obj);
}

3、交换方法的调用。

代码如下: 

+ (void)load {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        // 创建一个 实例方法对象1 ()
        Method orignViewDidLoad = class_getInstanceMethod([SwizzlingViewController class], @selector(test1));
        // 创建一个 实例方法对象2 ()
        Method replacingMethod = class_getInstanceMethod([SwizzlingViewController class], @selector(test2));
        
        // 交换2个方法对象的调用
        method_exchangeImplementations(orignViewDidLoad, replacingMethod);
    });
}

- (void)test1 {
    
    NSLog(@"test - 1");
}

- (void)test2 {
    
    NSLog(@"test - 2");
}

就可以自由扩展了,但使用需注意。

https://liangdahong.com/
原文地址:https://www.cnblogs.com/dahongliang/p/5499806.html