Runtime的应用场景

1、动态给分类添加属性

这个应该使用的比较频繁,通过runtime动态添加属性,可以给系统类添加自定义属性,灵活使用,可以带来神奇的效果。

//(block直接调用手势的action)
+ (instancetype)mm_gestureRecognizerWithActionBlock:(MMGestureBlock)block {
    __typeof(self) weakSelf = self;
    return [[weakSelf alloc]initWithActionBlock:block];
}
- (instancetype)initWithActionBlock:(MMGestureBlock)block {
    self = [self init];
    [self addActionBlock:block];
    [self addTarget:self action:@selector(invoke:)];
    return self;
}

- (void)addActionBlock:(MMGestureBlock)block {
    if (block) {
        objc_setAssociatedObject(self, &target_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
}
- (void)invoke:(id)sender {
    MMGestureBlock block = objc_getAssociatedObject(self, &target_key);
    if (block) {
        block(sender);
    }
}

2、方法的交换swizzling

这个方法,一般在特殊的情况下使用,可以将系统的方法转换成自定义的方法,在一些特殊的场景,比如iOS的平板开发及手机开发代码整合时,使用起来比较方便。

@implementation UIImage (hook)

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Class selfClass = object_getClass([self class]);
        
        SEL oriSEL = @selector(imageNamed:);
        Method oriMethod = class_getInstanceMethod(selfClass, oriSEL);
        
        SEL cusSEL = @selector(myImageNamed:);
        Method cusMethod = class_getInstanceMethod(selfClass, cusSEL);
        
        BOOL addSucc = class_addMethod(selfClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));
        if (addSucc) {
            class_replaceMethod(selfClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
        }else {
            method_exchangeImplementations(oriMethod, cusMethod);
        }
        
    });
}
+ (UIImage *)myImageNamed:(NSString *)name {
    
    NSString * newName = [NSString stringWithFormat:@"%@%@", @"new_", name];
    return [self myImageNamed:newName];
}

3、字典转模型

这个很常见,网上所有的字典转模型的三方框架最底层的实现原理莫过于此,你们去看一下就会明白了,比如MJExtension。

const char *kPropertyListKey = "YFPropertyListKey";
+ (NSArray *)yf_objcProperties
{
    /* 获取关联对象 */
    NSArray *ptyList = objc_getAssociatedObject(self, kPropertyListKey);
    /* 如果 ptyList 有值,直接返回 */
    if (ptyList) {
        return ptyList;
    }
    /* 调用运行时方法, 取得类的属性列表 */
    /* 成员变量:
     * class_copyIvarList(__unsafe_unretained Class cls, unsigned int *outCount)
     * 方法:
     * class_copyMethodList(__unsafe_unretained Class cls, unsigned int *outCount)
     * 属性:
     * class_copyPropertyList(__unsafe_unretained Class cls, unsigned int *outCount)
     * 协议:
     * class_copyProtocolList(__unsafe_unretained Class cls, unsigned int *outCount)
     */
    unsigned int outCount = 0;
    /**
     * 参数1: 要获取得类
     * 参数2: 类属性的个数指针
     * 返回值: 所有属性的数组, C 语言中,数组的名字,就是指向第一个元素的地址
     */
    /* retain, creat, copy 需要release */
    objc_property_t *propertyList = class_copyPropertyList([self class], &outCount);
    NSMutableArray *mtArray = [NSMutableArray array];
    /* 遍历所有属性 */
    for (unsigned int i = 0; i < outCount; i++) {
        /* 从数组中取得属性 */
        objc_property_t property = propertyList[i];
        /* 从 property 中获得属性名称 */
        const char *propertyName_C = property_getName(property);
        /* 将 C 字符串转化成 OC 字符串 */
        NSString *propertyName_OC = [NSString stringWithCString:propertyName_C encoding:NSUTF8StringEncoding];
        [mtArray addObject:propertyName_OC];
    }
    /* 设置关联对象 */
    /**
     *  参数1 : 对象self
     *  参数2 : 动态添加属性的 key
     *  参数3 : 动态添加属性值
     *  参数4 : 对象的引用关系
     */
    objc_setAssociatedObject(self, kPropertyListKey, mtArray.copy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    /* 释放 */
    free(propertyList);
    return mtArray.copy;
}
+ (instancetype)modelWithDict:(NSDictionary *)dict {
    /* 实例化对象 */
    id objc = [[self alloc]init];
    /* 使用字典,设置对象信息 */
    /* 1. 获得 self 的属性列表 */
    NSArray *propertyList = [self  yf_objcProperties];
    /* 2. 遍历字典 */
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        /* 3. 判断 key 是否字 propertyList 中 */
        if ([propertyList containsObject:key]) {
            /* 说明属性存在,可以使用 KVC 设置数值 */
            [objc setValue:obj forKey:key];
        }
    }];
    /* 返回对象 */
    return objc;
}

4、获取所有的私有属性和方法

这个在判断是否子类重写了父类的方法时会用到。

#pragma mark - 获取所有的属性(包括私有的)
- (void)getAllIvar {
    unsigned int count = 0;
    //Ivar:定义对象的实例变量,包括类型和名字。
    //获取所有的属性(包括私有的)
    Ivar *ivars= class_copyIvarList([UIPageControl class], &count);
    for (int i = 0; i < count; i++) {
        //取出成员变量
        Ivar ivar = ivars[i];
        
        NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
        NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        NSLog(@"属性 --> %@ 和 %@",name,type);
        
    }
    
}
#pragma mark - 获取所有的方法(包括私有的)
- (void)getAllMethod {
    unsigned int count = 0;
    //获取所有的方法(包括私有的)
    Method *memberFuncs = class_copyMethodList([UIPageControl class], &count);
    for (int i = 0; i < count; i++) {
        
        SEL address = method_getName(memberFuncs[i]);
        NSString *methodName = [NSString stringWithCString:sel_getName(address) encoding:NSUTF8StringEncoding];
        
        NSLog(@"方法 : %@",methodName);
    }
    
}


5、对私有属性修改

好像没遇到过具体需要使用地方。

#pragma mark - 对私有变量的更改
- (void)changePrivate {
    Person *onePerson = [[Person alloc] init];
    NSLog(@"Person属性 == %@",[onePerson description]);
    
    unsigned  int count = 0;
    Ivar *members = class_copyIvarList([Person class], &count);
    
    for (int i = 0; i < count; i++){
        Ivar var = members[i];
        const char *memberAddress = ivar_getName(var);
        const char *memberType = ivar_getTypeEncoding(var);
        NSLog(@"获取所有属性 = %s ; type = %s",memberAddress,memberType);
    }
    //对私有变量的更改
    Ivar m_address = members[1];
    object_setIvar(onePerson, m_address, @"上海");
    NSLog(@"对私有变量的(地址)进行更改 : %@",[onePerson description]);
    
}

6、归档:解档

快速定义归档和解档属性

@implementation MMModel

- (void)encodeWithCoder:(NSCoder *)encoder {
    unsigned int count = 0;
    //  利用runtime获取实例变量的列表
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        //  取出i位置对应的实例变量
        Ivar ivar = ivars[i];
        //  查看实例变量的名字
        const char *name = ivar_getName(ivar);
        //  C语言字符串转化为NSString
        NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        //  利用KVC取出属性对应的值
        id value = [self valueForKey:nameStr];
        //  归档
        [encoder encodeObject:value forKey:nameStr];
    }
    
    //  记住C语言中copy出来的要进行释放
    free(ivars);
    
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i ++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            
            //
            NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
            id value = [decoder decodeObjectForKey:key];
            //  设置到成员变量身上
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}


7、动态的添加方法

这个我也没用过,不过理解了消息转发的整个流程,就能够理解为什么这样行得通。

// 默认方法都有两个隐式参数,
void eat(id self,SEL sel){
    NSLog(@"%@ %@",self,NSStringFromSelector(sel));
    NSLog(@"动态添加了一个方法");

}

// 当一个对象调用未实现的方法,会调用这个方法处理,并且会把对应的方法列表传过来.
// 刚好可以用来判断,未实现的方法是不是我们想要动态添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    
    if (sel == NSSelectorFromString(@"eat")) {
        // 注意:这里需要强转成IMP类型
        class_addMethod(self, sel, (IMP)eat, "v@:");
        return YES;
    }
    // 先恢复, 不然会覆盖系统的方法
    return [super resolveInstanceMethod:sel];
}

8、给UIButton添加点击事件的block

  1. 首先给需要使用的 block 类型定义一个别名:
typedef void(^MHButtonActionCallBack)(UIButton *button);

这样当需要使用这种 bolck 类型的时候, 就不需要把注意力放在 block 的具体内容上了, 即: 不需要考虑 block 的传参和返回值类型了.

  1. 利用iOS runtime 应用之给 NSString 添加对象属性和非对象属性中介绍的原理给UIButton"添加"一个MHButtonActionCallBack类型的属性(诚然, 这种"添加"并不是严格意义上的添加, 只不过是添加了一对gettersetter 方法而已):
- (void)setMHCallBack:(MHButtonActionCallBack)callBack {
    objc_setAssociatedObject(self, &_callBack, callBack, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (MHButtonActionCallBack)getMHCallBack {
     return (MHButtonActionCallBack)objc_getAssociatedObject(self, &_callBack);
}

这样就可以放心大胆的使用UIButtonsetMHCallBack:getMHCallBack:方法进行赋值和取值操作了.

  1. 为了便于调用, 还要把上一步"添加"的"属性", 封装到UIButton 内部, 只暴露出下面的方法:
- (void)addMHClickAction:(MHButtonActionCallBack)callBack;

至此, 当需要给UIButton 添加点击事件的时候, 就可以直接调用这个方法就可以了.

附上完整代码:
UIButton+MHExtra.h

#import <UIKit/UIKit.h>

typedef void(^MHButtonActionCallBack)(UIButton *button);

@interface UIButton (MHExtra)


/**
 *  @brief replace the method 'addTarget:forControlEvents:'
 */
- (void)addMHCallBackAction:(MHButtonActionCallBack)callBack forControlEvents:(UIControlEvents)controlEvents;

/**
 *  @brief replace the method 'addTarget:forControlEvents:UIControlEventTouchUpInside'
 *  the property 'alpha' being 0.5 while 'UIControlEventTouchUpInside'
 */
- (void)addMHClickAction:(MHButtonActionCallBack)callBack;

@end

UIButton+MHExtra.m

#import "UIButton+MHExtra.h"
#import <objc/runtime.h>


/**
 *  @brief add action callback to uibutton
 */
@interface UIButton (MHAddCallBackBlock)

- (void)setMHCallBack:(MHButtonActionCallBack)callBack;
- (MHButtonActionCallBack)getMHCallBack;

@end

@implementation UIButton (MHAddCallBackBlock)

static MHButtonActionCallBack _callBack;

- (void)setMHCallBack:(MHButtonActionCallBack)callBack {
    objc_setAssociatedObject(self, &_callBack, callBack, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (MHButtonActionCallBack)getMHCallBack {
     return (MHButtonActionCallBack)objc_getAssociatedObject(self, &_callBack);
}

@end;


@implementation UIButton (MHExtra)

/**
 *  @brief replace the method 'addTarget:forControlEvents:UIControlEventTouchUpInside'
 *  the property 'alpha' being 0.5 while 'UIControlEventTouchUpInside'
 */
- (void)addMHClickAction:(MHButtonActionCallBack)callBack {
    [self addMHCallBackAction:callBack forControlEvents:(UIControlEventTouchUpInside)];
    [self addTarget:self action:@selector(mhTouchDownAction:) forControlEvents:(UIControlEventTouchDown)];
    [self addTarget:self action:@selector(mhTouchUpAction:) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel | UIControlEventTouchDragOutside)];
}

/**
 *  @brief replace the method 'addTarget:forControlEvents:'
 */
- (void)addMHCallBackAction:(MHButtonActionCallBack)callBack forControlEvents:(UIControlEvents)controlEvents{
    [self setMHCallBack:callBack];
    [self addTarget:self action:@selector(mhButtonAction:) forControlEvents:controlEvents];
}

- (void)mhButtonAction:(UIButton *)btn {
    self.getMHCallBack(btn);
}

- (void)mhTouchDownAction:(UIButton *)btn {
    btn.enabled = NO;
    btn.alpha = 0.5f;
}

- (void)mhTouchUpAction:(UIButton *)btn {
    btn.enabled = YES;
    btn.alpha = 1.0f;
}

@end

从现在开始, 当需要给UIBuootn 添加点击事件的时候, 就不需要先调用addTarget: action: forControlEvents:, 然后在实现其中的action 方法了, 直接:

    [btn addMHClickAction:^(UIButton *button) {
        NSLog(@"clicked button");
    }];

9、利用runtime实现万能跳转

1.万能跳转的应用场景:

(1)手机App通过推送过来的数据内容来跳转不同的界面,并把界面数据展示出来。
(2)手机内部根据不同的cell的点击事件,不同的数据跳转不同的界面。

2.工作的流程图:

通过动态返回的数据中的class类名,来去查询class是不是存在:(1)存在则获取实例对象然后通过kVC来绑定数据然后去跳转。(2)不存在则动态创建class及其变量,然后手动创建实例对象在通过KVC来绑定数据,最后跳转。

 

流程图.png

3.主要方法:

//创建Class
    objc_allocateClassPair(Class superclass, const char * name, size_t extraBytes)
//注册Class
    void objc_registerClassPair(Class cls)
//添加变量
    class_addIvar(Class cls, const char * name,size_t size, uint8_t alignment , const char * types)
//添加方法
    class_addMethod(Class cls, SEL name, IMP  imp, const char * types)
//获取属性
    class_getProperty(Class  cls, const char * name)
//获取实例变量
    class_getInstanceVariable(Class cls, const char * name)

4.代码实现:

1、工程中新建三个控制器,命名为
FirstViewController
SecondViewController
ThredViewController
每一个控制器的viewDidLoad方法里面的内容为

self.view.backgroundColor = [UIColor redColor];
    
    UILabel * titleLab = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 40)];
    titleLab.textColor = [UIColor blackColor];
    [self.view addSubview:titleLab];
    titleLab.text =self.name;

然后在ViewController模拟根据不同数据跳转不同界面,代码如下

#import "ViewController.h"
#import <objc/message.h>

@interface ViewController ()

@property (nonatomic, weak) UISegmentedControl * seg;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor yellowColor];
    
    NSArray * array = @[@"消息1",@"消息2",@"消息3",@"消息4"];
    UISegmentedControl * seg = [[UISegmentedControl alloc]initWithItems:array];
    seg.frame = CGRectMake(70, 200, 240, 45);
    [self.view addSubview:seg];
    seg.selectedSegmentIndex = 0;
    self.seg = seg;
    
    UIButton * jupBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    jupBtn.frame = CGRectMake(100, 250, 60, 45);
    [jupBtn setTitle:@"跳转" forState:UIControlStateNormal];
    [jupBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    jupBtn.backgroundColor = [UIColor redColor];
    [self.view addSubview:jupBtn];
    [jupBtn addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    
    //创建Class
    //objc_allocateClassPair(Class superclass, const char * name, size_t extraBytes)
    //注册Class
    //void objc_registerClassPair(Class cls)
    //添加变量
    //class_addIvar(Class cls, const char * name,size_t size, uint8_t alignment , const char * types)
    //添加方法
    //class_addMethod(Class cls, SEL name, IMP  imp, const char * types)
    //获取属性
    //class_getProperty(Class  cls, const char * name)
    //获取实例变量
    //class_getInstanceVariable(Class cls, const char * name)
}

-(void)action{
    
    NSDictionary * infoDic = nil;
    
    switch (self.seg.selectedSegmentIndex) {
        case 0:
            infoDic = @{@"class":@"FirstViewController",
                        @"property":@{
                                @"name":@"尼古拉斯赵四"
                                }
                        };
            break;
        case 1:
            infoDic = @{@"class":@"SecondViewController",
                        @"property":@{
                                @"age":@"26",
                                @"sex":@"男"
                                }
                        };
            break;
        case 2:
            infoDic = @{@"class":@"ThredViewController",
                        @"property":@{
                                @"teacher":@"王老师",
                                @"money":@"5000"
                                }
                        };
            break;
        case 3:
            //NewViewController
            infoDic = @{@"class":@"WorkerController",
                        @"property":@{
                                @"phoneNumber":@"17710948530"
                                }
                        };
            break;
            
        default:
            break;
    }
    
    [self pushToControllerWithData:infoDic];
    
}
-(void)pushToControllerWithData:(NSDictionary * )vcData{
    //1.获取class
    const char * className = [vcData[@"class"] UTF8String];
    Class cls = objc_getClass(className);
    if(!cls){
        //创建新的类,并添加变量和方法
        Class superClass = [UIViewController class];
        cls = objc_allocateClassPair(superClass, className, 0);
        //添加phoneNumber变量
        class_addIvar(cls, "phoneNumber", sizeof(NSString *), log2(sizeof(NSString *)), @encode(NSString *));
        //添加titleLab控件
        class_addIvar(cls, "titleLab", sizeof(UILabel *), log2(sizeof(UILabel *)), @encode(UILabel *));
        //添加方法,方法交换,执行viewDidLoad加载
        Method method = class_getInstanceMethod([self class], @selector(workerLoad));
        IMP methodIMP = method_getImplementation(method);
        const char * types = method_getTypeEncoding(method);
        class_addMethod(cls, @selector(viewDidLoad), methodIMP, types);
    }
    //2.创建实例对象,给属性赋值
    id instance = [[cls alloc]init];
    NSDictionary * values = vcData[@"property"];
    [values enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        //检测是否存在为key的属性
        if(class_getProperty(cls, [key UTF8String])){
            [instance setValue:obj forKey:key];
        }
        //检测是否存在为key的变量
        else if (class_getInstanceVariable(cls, [key UTF8String])){
            [instance setValue:obj forKey:key];
        }
    }];
    
    //2.跳转到对应的界面
    [self.navigationController pushViewController:instance animated:YES];
    
}

-(void)workerLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor greenColor];
    //初始化titleLab
    [self setValue:[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 40)] forKey:@"titleLab"];
    UILabel * titleLab = [self valueForKey:@"titleLab"];
    //添加到视图上
    [[self valueForKey:@"view"] performSelector:@selector(addSubview:) withObject:titleLab];
    titleLab.text =[self valueForKey:@"phoneNumber"];
    titleLab.textColor = [UIColor blackColor];
    
}

@end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值