iOS-RunTime 动态添加属性和方法

1.1动态添加属性:

#import "Person.h"
#import 

const char *homeKey = "homeKey";
@implementation Person

@dynamic home;
//通过运行时,动态添加属性
- (void)setHome:(NSString *)home {
    [self willChangeValueForKey:home];
    objc_setAssociatedObject(self, &homeKey, home, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:home];
}
-(NSString *)home {
   return  objc_getAssociatedObject(self, &homeKey);
}

@end

1.2调用:

Person *p = Person.new;
    p.home  = @"上海虹口区";
    NSLog(@"my home is %@",p.home);

1.3输出结果:

my home is 上海虹口区

2.1动态添加方法

//动态添加方法
    SEL pSelector = NSSelectorFromString(@"addMethod:");
    class_addMethod(p.class, pSelector, (IMP)pMethod, "v@:@");
    
    if ([p respondsToSelector:pSelector]) {
        [p performSelector:pSelector withObject:@"message"];
    }

void pMethod(id self,SEL _cmd,NSString *str){
    NSLog(@"给person添加一个方法addMethod %@",str);
}

2.2输出结果:

给person添加一个方法addMethod message

3.1动态添加属性检测

unsigned int count = 0;
    
    Ivar *vars = class_copyIvarList(p.class, &count);
    for (NSInteger i = 0; i < count; i++) {
        Ivar var = vars[i];
        NSLog(@"v = %s",ivar_getName(var));//通过取成员变量的方式无法拿到动态添加的属性home
    }
    objc_property_t *pros =class_copyPropertyList(p.class, &count);
    
    for (NSInteger i = 0; i < count; i++) {
        objc_property_t var = pros[i];
        NSLog(@"p = %s",property_getName(var));//通过取全部属性的方式可以拿到动态添加的属性home
    }

3.2检测结果

p = home

祭出demo
更新时间2018-09-21

你可能感兴趣的:(iOS-RunTime 动态添加属性和方法)