Learning AV Foundation技术学习

iOS底层原理(二):Runtime研究(二)

2018-11-01  本文已影响6人  iOS猿_员

这个篇幅我们继续研究runtime,这里给大家介绍runtime的api

下面我们来玩一下这些常用的api

//交换方法
        Method m1 = class_getInstanceMethod(self, @selector(viewWillAppear:));
        Method m2 = class_getInstanceMethod(self, @selector(tz_viewWillAppear:));        
        method_exchangeImplementations(m1, m2);
// 关联属性
- (void)setViewColor:(NSString *)viewColor{

    objc_setAssociatedObject(self, &associatedObjectKey, @"addProperty", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)viewColor{
    return objc_getAssociatedObject(self, &associatedObjectKey);
}

 /// 创建一类对
    Class TZCat = objc_allocateClassPair([NSObject class], "TZCat", 0);

    /// 添加实例变量
    // const char* types= "v@:"
    NSString* name = @"name";

    class_addIvar(TZCat, name.UTF8String, sizeof(id), log2(sizeof(id)), @encode(id));

    // 添加方法
    class_addMethod(TZCat, @selector(hunting), (IMP)hunting, "v@:");

    /// 注册类
    objc_registerClassPair(TZCat);

    // 创建实例对象
    id cat = [[TZCat alloc] init];
    [cat setValue:@"Tom" forKey:@"name"];
    NSLog(@"name = %@", [cat valueForKey:name]);

    /// 方法调用
    [cat performSelector:@selector(hunting)];

  // 获取成员变量列表
    unsigned int count = 0;
    Ivar* ivars = class_copyIvarList([self class], &count);

    for (int i = 0; i < count; i++) {
        Ivar var = ivars[i];
        const char* name = ivar_getName(var);
        NSString* key = [NSString stringWithUTF8String:name];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }

    free(ivars);

以上就是这篇文章的全部内容了,希望本文的内容对大家具有一定的参考学习价值,同时欢迎大家进入小编交流群:624212887,一起交流学习,谢谢大家的支持

上一篇下一篇

猜你喜欢

热点阅读