runtime往事一二

作者: 叶子扬 | 来源:发表于2018-11-27 20:39 被阅读6次

runtime 的几个应用场景:

  • 消息转发
  • method siwizzling
  • 归解档、模式互转
  • 自定义KVO

消息转发

消息转发机制的流程:

  • 动态方法解析
  • 快速转发
  • 慢速转发(也就是完整的消息转发流程)
消息转发机制.png

动态方法解析

给person类的.h添加一个方法yy_sendMessage,但是没有实现,
运行[[Person new] yy_sendMessage:@"yy_msg"];这个方法会报错:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person yy_sendMessage:]: unrecognized selector sent to instance 0x6000025e0b50'

动态方法解析可以实现动态的为当前类添加方法:

@implementation Person

void yy_sendMessage(id self, SEL _cmd, NSString *msg)
{
    NSLog(@"person--%@",msg);
}

+ (BOOL)resolveInstanceMethod:(SEL)sel
{
    NSString *methodName = NSStringFromSelector(sel);
    if ([methodName isEqualToString:@"yy_sendMessage:"]) {
        BOOL flag = class_addMethod(self, sel, (IMP)yy_sendMessage, "v@:@");
        return flag;
    }
    return NO;
}

@end

再次运行,程序正常并打印消息

person--yy_msg

快速转发

如果Person类没有实现resolveInstanceMethod:方法,或者返回NO,可以通过快速转发的方式,把消息发给别的对象,这里把消息转给Car,前提是Car要有实现这个方法

@interface Car : NSObject
- (void)yy_sendMessage:(NSString *)msg;
@end

@implementation Car

- (void)yy_sendMessage:(NSString *)msg
{
    NSLog(@"car--%@",msg);
}

@end
@implementation Person
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    NSString *methodName = NSStringFromSelector(aSelector);
    if ([methodName isEqualToString:@"yy_sendMessage:"]) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
    }
    return [super methodSignatureForSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    SEL sel = anInvocation.selector;
    Car *car = [Car new];
    if ([car respondsToSelector:sel]) {
        [anInvocation invokeWithTarget:car];
    }else{
        [super forwardInvocation:anInvocation];
    }
}
@end

打印结果:

car--yy_msg

重写doesNotRecognizeSelector:

如果forwardInvocation:没有找到合适的消息处理者,重写doesNotRecognizeSelector:可以让app继续运行:

- (void)doesNotRecognizeSelector:(SEL)aSelector
{
    NSLog(@"找不到方法,app继续运行");
}

method siwizzling

方法交换,就是把我们的方法O和系统的方法S交换,在执行S方法的时候,及时运行的是O方法的逻辑。

@interface UITableView (YYDefaultDisplayView)
@property (nonatomic, strong) UILabel *nodataTipsView; 
@end
    
@implementation UITableView (YYDefaultDisplayView)

+ (void)load{
    static dispatch_once_t onceToken;
    // 确保只会执行一次 (防止调皮的童鞋手动再调用load方法)
    dispatch_once(&onceToken, ^{
        Method originMethod = class_getInstanceMethod(self, @selector(reloadData));
        Method swizzlingMethod = class_getInstanceMethod(self, @selector(yy_reloadData));
        
        // 互换方法
        method_exchangeImplementations(originMethod, swizzlingMethod);
    });
}

// 卧底
- (void)yy_reloadData{
    // yy_reloadData实际指向reloadData,相当于调用系统的方法
    [self yy_reloadData];
    
    // 这里添加我们想要做的事情
    [self showDefaultVeiw];
}

- (void)showDefaultVeiw{
    id<UITableViewDataSource> dataSource = self.dataSource;
    NSInteger section = [dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)] ? [dataSource numberOfSectionsInTableView:self] : 1;
    NSInteger row = 0;
    for (NSInteger i= 0; i < section; i ++) {
        row = [dataSource tableView:self numberOfRowsInSection:section];
    }
    
    if (row == 0) {
        self.nodataTipsView = [[UILabel alloc] init];
        self.nodataTipsView.text  = @"暂时无数据,再刷新试试?";
        self.nodataTipsView.backgroundColor = UIColor.yellowColor;
        self.nodataTipsView.textAlignment = NSTextAlignmentCenter;
        self.nodataTipsView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        [self addSubview:self.nodataTipsView];
    }else{
        self.nodataTipsView.hidden = YES;
    }
}

#pragma mark - getting && setting
- (void)setNodataTipsView:(UILabel *)nodataTipsView
{
    objc_setAssociatedObject(self, @selector(nodataTipsView), nodataTipsView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UILabel *)nodataTipsView
{
    return objc_getAssociatedObject(self, _cmd);
}

@end

这里有几个值得思考的点:

  1. 为什么选择在laod方法里交换方法?
  2. 为什么要确保执行一次?
  3. yy_reloadData里又调用了yy_reloadData,会造成死循环麽?
  4. set方法和get方法里,使用了_cmd作为关联key,为什么?(都是const void *key类型)

详情见这里

归解档/模式互转

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age; 

- (instancetype)initWithDictionary:(NSDictionary *)dictionary;
- (NSDictionary *)convertModelToDictionary;

@end
#import "Person.h"
#import <objc/message.h>

@implementation Person

// 字典->模型
- (instancetype)initWithDictionary:(NSDictionary *)dictionary{
    self = [super init];
    if (self) {
        for (NSString *key in dictionary.allKeys) {
            
            // 通过key构建set方法
            NSString *methodName = [NSString stringWithFormat:@"set%@:",key.capitalizedString];
            SEL sel = NSSelectorFromString(methodName);
            if (sel) {
                /*
                 指针函数的形式:
                 returnType (*functionName) (param1, param2, ...)
                 void (*)(id, SEL, id)
                 
                 使用指针调用函数:
                 (returnType (*functionName) (param1, param2, ...))
                 */
                NSString *value = dictionary[key];
                ((void (*)(id, SEL, id))objc_msgSend)(self, sel, value);
            }
        }
    }
    return self;
}

// 模型->字典
- (NSDictionary *)convertModelToDictionary{
    
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList(self.class, &count);
    
    if (count == 0) {
        free(properties);
        return nil;
    }
    
    NSMutableDictionary *dic = NSMutableDictionary.dictionary;
    for (int i = 0; i < count; i ++) {
        const char *propertyName = property_getName(properties[i]);
        NSString *name = [NSString stringWithUTF8String:propertyName];
        SEL sel = NSSelectorFromString(name);
        if (sel) {
            // 通过get方法获取value
            NSString *value =  ((id (*)(id, SEL))objc_msgSend)(self, sel);
            
            if (value) {
                dic[name] = value;
            }else{
                dic[name] = @"";
            }
        }
    }
    
    // 释放
    free(properties);
    return dic;
}
@end
// 测试:
NSDictionary *dic = @{@"name": @"iO骨灰级菜鸟", @"age": @(18)};
    Person *p = [[Person alloc] initWithDictionary:dic];
    
    NSLog(@"name: %@  age:%@",p.name, p.age);
    
    NSDictionary *dic2 = [p convertModelToDictionary];
    NSLog(@"dic2:%@",dic2);
 
 // 打印:
name: iO骨灰级菜鸟  age:18
dic2:{
    age = 18;
    name = "iO\U9aa8\U7070\U7ea7\U83dc\U9e1f";
}

person类提供了字典和模型互转的方法,分别对应属性的set方法和get方法。核心代码是通过函数指针的方式运行objc_sendMsg()方法。

字典转模型里,注意方法函数名字大写的拼接处理,改进的空间有:

  1. 兼容性处理:判断参数是否是字典,字典多层嵌套等
  2. 性能优化:缓存结果、使用更底层的函数以提高性能等

模型转字典里,注意释放变量。

自定义KVO

KVO的底层实现也是基于runtime。当一个对象Obj被监听的时候,系统会为Obj创建一个子类,并加上一个前缀NSKVONotifing_Obj。接着把isa指针也改为指向新的子类,所以苹果说不要通过isa来判断这个类的真实类型。同时,Apple 还重写了 -class 方法,企图欺骗我们这个类没有变,就是原本那个类。当然,还要重写set方法,在set方法里实现通知的逻辑。具体实现可以看我的这篇博文

相关文章

  • runtime往事一二

    runtime 的几个应用场景: 消息转发 method siwizzling 归解档、模式互转 自定义KVO 消...

  • 往事一二

    当我说“未来”的时候,我刚一念它就成了过去。 2010年,我带着一身青涩、憧憬和一点忐忑走进了X行。分配的网...

  • 往事一二

    周末休息在家收拾整理书柜,无意间翻出了以前的日记。随手翻开日记本,看着上面记录的点点滴滴,不由得心中感慨万...

  • 往事一二

    今天重阳,贵阳的太阳难得地灿烂,每当这个时候,我就会担心脸上新添的小雀斑。斑斑点点,集聚一起,跃跃欲飞的感觉。 遥...

  • 往事一二

    昨夜在漫散的睡意中我想起了外公,外公年事已高,有些糊涂了,也不如往常那般与我亲切。这几年回家的次数越来越少,每...

  • 往事一二

    最近,我回家了。 回家意味着两代人思想的碰撞。很多时候,对于父母近似迂腐的观点,我只能选择微笑。而此次在家...

  • 往事一二

    (一) 头绑着绷带,上学去了。 这种装束出现在教室,自然而然便引起了老师同学们的注意,尤其是课间,各种掺杂着怜悯与...

  • 往事一二

    纯净的阳光静静地照在收获的稻田里, 悠闲的白云懒散地漂浮在蔚蓝的天空中, 当秋风再一次吹起片片落叶在我裤管的时候,...

  • 往事一二

    一 十岁,那时的我小学三年级在读。父亲在县城里的全县唯一一所高级中学任教。此时,小弟尚安在,为了给...

  • 往事矫情一二

    不知为何, 今天突然又莫名矫情了一把 感觉自己自高考后 不管是大学里每年都愁找兼职的寒暑假 还是离职后的空档期 一...

网友评论

    本文标题:runtime往事一二

    本文链接:https://www.haomeiwen.com/subject/cvbnqqtx.html