美文网首页
RunTime 之其他实践运用

RunTime 之其他实践运用

作者: 進无尽 | 来源:发表于2018-03-07 08:45 被阅读0次

    前言

    有关Runtime的知识总结,我本来想集中写成一篇文章的,但是最后发现实在是太长,而且不利于阅读,最后分成了如下几篇:


    本文主要罗列在项目实践中RunTime的综合使用:

    实现NSCoding的自动归档和自动解档;

    如果你实现过自定义模型数据持久化的过程,那么你也肯定明白,如果一个模型有许多个属性,那么我们需要对每个属性都实现一遍encodeObject 和decodeObjectForKey方法,如果这样的模型又有很多个,这还真的是一个十分麻烦的事情。下面来看看简单的实现方式。

    //归档
    - (instancetype)initWithCoder:(NSCoder *)aDecoder{
        
        if (self = [super init]) {
            Class c = self.class;
            // 截取类和父类的成员变量
            while (c && c != [NSObject class]) {
                unsigned int count = 0;
                Ivar *ivars = class_copyIvarList(c, &count);
                for (int i = 0; i < count; i++) {
                    NSString *key = [NSString stringWithUTF8String:ivar_getName(ivars[i])];
                    id value = [aDecoder decodeObjectForKey:key];
                    if (value){
                         [self setValue:value forKey:key];
                    }
                }
                // 获得c的父类
                c = [c superclass];
                free(ivars);
            }
        }
        return self;
    }
    //解档
    - (void)encodeWithCoder:(NSCoder *)aCoder{
        
        Class c = self.class;
        // 截取类和父类的成员变量
        while (c && c != [NSObject class]) {
            unsigned int count = 0;
            Ivar *ivars = class_copyIvarList(c, &count);
            for (int i = 0; i < count; i++) {
                Ivar ivar = ivars[i];
                NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
                id value = [self valueForKey:key];
                if (value){
                     [aCoder encodeObject:value forKey:key];
                 }
            }
            c = [c superclass];
            // 释放内存
            free(ivars);
        }
    }
    
    

    依据上面的原理我们就可以给NSObject做一个分类,让我们不需要每次都写这么一长串代码,只要实现一小段代码就可以让一个对象具有归解档的能力。

    注意,下面的代码我换了一个方法名(不然会覆盖系统原来的方法!),加了一个忽略属性方法是否被实现的判断,并加上了对父类属性的归解档循环。

    NSObject+Extension.h
    #import <Foundation/Foundation.h>
    
    @interface NSObject (Extension)
    
    - (NSArray *)ignoredNames;
    - (void)encode:(NSCoder *)aCoder;
    - (void)decode:(NSCoder *)aDecoder;
    
    @end
    
    NSObject+Extension.m
    #import "NSObject+Extension.h"
    #import <objc/runtime.h>
    
    @implementation NSObject (Extension)
    
    - (void)decode:(NSCoder *)aDecoder {
    // 一层层父类往上查找,对父类的属性执行归解档方法
    Class c = self.class;
    while (c &&c != [NSObject class]) {
        
        unsigned int outCount = 0;
        Ivar *ivars = class_copyIvarList(c, &outCount);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            
            // 如果有实现该方法再去调用
            if ([self respondsToSelector:@selector(ignoredNames)]) {
                if ([[self ignoredNames] containsObject:key]) continue;
            }
            
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
        free(ivars);
        c = [c superclass];
      } 
    }
    
    - (void)encode:(NSCoder *)aCoder {
    // 一层层父类往上查找,对父类的属性执行归解档方法
    Class c = self.class;
    while (c &&c != [NSObject class]) {
        
        unsigned int outCount = 0;
        Ivar *ivars = class_copyIvarList([self class], &outCount);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            
            // 如果有实现该方法再去调用
            if ([self respondsToSelector:@selector(ignoredNames)]) {
                if ([[self ignoredNames] containsObject:key]) continue;
            }
            
            id value = [self valueForKeyPath:key];
            [aCoder encodeObject:value forKey:key];
        }
        free(ivars);
        c = [c superclass];
      }
    }
    @end
    

    上面分类使用方法:在需要归解档的对象中实现下面方法即可:

    // 设置需要忽略的属性
    - (NSArray *)ignoredNames {
        return @[@"bone"];
    }
    
    // 在系统方法内来调用我们的方法
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super init]) {
              [self decode:aDecoder];
        }
          return self;
      }
    
    - (void)encodeWithCoder:(NSCoder *)aCoder {
          [self encode:aCoder];
    }
    

    或者在BaseModel这个基类中实现,在子类中就可以直接调用了,超级方便。

    顺便补充下,归档、解档自定义对象的过程如下:

    NSString *name = @"小红";
    NSInteger age = 22;
    NSString *address = @"西安";
    UIImage *photo = [UIImage imageNamed:@"5.png"];
    Archiver *archiver = [[Archiver alloc]init];
    archiver.name = name;
    archiver.age = age;
    archiver.address = address;
    archiver.photo = photo;
    
    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver *archive = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archive encodeObject:archiver forKey:@"arc"];
    [archive finishEncoding];
    [data writeToFile:[self GetThefilePath:@"archiver.archiver"] atomically:YES];
    
    
    NSMutableData *data = [[NSMutableData alloc]initWithContentsOfFile:[self GetThefilePath:@"archiver.archiver"]];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    Archiver *arch = [unarchiver decodeObjectForKey:@"arc"];
    [unarchiver finishDecoding];
    

    关于对象归档时需要注意的是:首先对象需要遵循 <NSCoding> 协议,然后在 .m 中实现
    initWithCoder:和 encodeWithCoder 方法即可。对于像下面这样的属性,也不用特殊处理,只是products 中的 JVShopcartProductModel 类中也需要遵循<NSCoding> 协议并实现上面两个归档方法才行。这样一个属性中有另外对象所组成的数组的对象就可以完成归档了。

    @interface JVShopcartBrandModel : NSObject
    <NSCoding>
    @property (nonatomic, copy) NSString *brandId;
    @property (nonatomic, strong) NSMutableArray<JVShopcartProductModel *> *products;
    @property (nonatomic, copy) NSString *brandName;
    @property (nonatomic, assign)BOOL isSelected; //记录相应section是否全选(自定义)
    @property (nonatomic, strong) NSMutableArray *selectedArray;    //结算时筛选出选中的商品(自定义)
    @end
    
    这里特别要说下,关于旧版本APP和新版本APP中的Model属性不同时,如果我们不做判断,是会崩溃的,操作很简单就是在[self setValue:value forKey:key]; 时判断下这个 value存在不存在,存在的情况下再保存。使用数据库时,主键值的变更不作处理同样会造成崩溃。

    实现字典和模型的自动转换。

    原理描述:用runtime提供的函数遍历Model自身所有属性,如果属性在json中有对应的值,则将其赋值。

    利用runtime 获取所有属性来进行字典转模型,其实就是根据创建的Model,把网络返回来的字典数据赋值到Model中,对Model属性进行赋值。看以下代码时,以Model为中心,而不是以dic中的数据为中心。

    以往我们都是利用KVC进行字典转模型,但是它还是有一定的局限性,例如:模型属性和键值对对应不上会crash(虽然可以重写setValue:forUndefinedKey:方法防止报错),模型属性是一个对象或者数组时不好处理等问题,所以无论是效率还是功能上,利用runtime进行字典转模型都是比较好的选择。

    字典转模型我们需要考虑三种特殊情况:
    1.当字典的key和模型的属性匹配不上
    2.模型中嵌套模型(模型属性是另外一个模型对象)
    3.数组中装着模型(模型的属性是一个数组,数组中是一个个模型对象)

    第三种情况是模型的属性是一个数组,数组中是一个个模型对象,例如下面的数据我就可以通过books[0].name
    获取到C语言程序设计

    JSON数据

    我们既然能获取到属性类型,那就可以拦截到模型的那个数组属性,进而对数组中每个模型遍历并字典转模型,但是我们不知道数组中的模型都是什么类型,我们可以声明一个方法,该方法目的不是让其调用,而是让其实现并返回模型的类型。这块语言可能解释不太清楚,可以参考我的demo,直接运行即可。

    NSObject+JSONExtension.h
    
    // 返回数组中都是什么类型的模型对象- (NSString *)arrayObjectClass ;
    
    NSObject+JSONExtension.m
    
    #import "NSObject+JSONExtension.h"
    #import <objc/runtime.h>
    
    @implementation NSObject (JSONExtension)
    
    - (void)setDict:(NSDictionary *)dict {
    
      Class c = self.class;
      while (c &&c != [NSObject class]) {
    
        unsigned int outCount = 0;
        Ivar *ivars = class_copyIvarList(c, &outCount);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
    
            // 成员变量名转为属性名(去掉下划线 _ )
            key = [key substringFromIndex:1];
            // 取出字典的值
            id value = dict[key];
    
            // 如果模型属性数量大于字典键值对数理,模型属性会被赋值为nil而报错
            if (value == nil) continue;
    
            // 获得成员变量的类型
            NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
    
            // 如果属性是对象类型
            NSRange range = [type rangeOfString:@"@"];
            if (range.location != NSNotFound) {
                // 那么截取对象的名字(比如@"Dog",截取为Dog)
                type = [type substringWithRange:NSMakeRange(2, type.length - 3)];
                // 排除系统的对象类型
                if (![type hasPrefix:@"NS"]) {
                    // 将对象名转换为对象的类型,将新的对象字典转模型(递归)
                    Class class = NSClassFromString(type);
                    value = [class objectWithDict:value];
    
                }else if ([type isEqualToString:@"NSArray"]) {
    
                    // 如果是数组类型,将数组中的每个模型进行字典转模型,先创建一个临时数组存放模型
                    NSArray *array = (NSArray *)value;
                    NSMutableArray *mArray = [NSMutableArray array];
    
                    // 获取到每个模型的类型
                    id class ;
                    if ([self respondsToSelector:@selector(arrayObjectClass)]) {
                        # arrayObjectClass 这个方法返回 数组里的对象类型,因为是数据里面的对象一般是同一个类型的。
                        #这里写成一个方法,而不是写死,也是方便代码封装后继承重写复用。
                        NSString *classStr = [self arrayObjectClass];
                        class = NSClassFromString(classStr);
                    }
                    // 将数组中的所有模型进行字典转模型
                    for (int i = 0; i < array.count; i++) {
                        [mArray addObject:[class objectWithDict:value[i]]];
                    }
                    value = mArray;
                }
            }
    
            // 将字典中的值设置到模型上
            [self setValue:value forKeyPath:key];
        }
        free(ivars);
        c = [c superclass];
      }
    }
     #相当于一个递归调用,循环每一个属性,每次只讨论一个属性。
    + (instancetype )objectWithDict:(NSDictionary *)dict {
        NSObject *obj = [[self alloc]init];
        [obj setDict:dict];
        return obj;
    }  
    @end
    

    通过 RunTime+KVC 修改系统原生控件的私有属性

    举个例子:给UITabBarItem添加Badge

    Xcode自带的UI视图调试神器

    运行Demo后点击打开,可清楚的看到底部栏的UITabBarItem内有一个UITabBarButton,其下属还有一个UITabBarSwappableImageView的图片控件,我们要找的就是这个UITabBarSwappableImageView

    接下来就是要获取这个UITabBarSwappableImageView,我们可以使用Runtime + KVC 的方式:

    1. 先利用runtime获的UITabBarButton的对象名称, 最后打印的结果为(因打印的内容太多,这里只贴出最关键的结果):

        打印结果: UITabBarItem内的成员变量类型为: @"UITabBarButton",名字为: _view
    

    2. 再使用KVC取出这个UITabBarButton对象,遍历出UITabBarSwappableImageView对象
    得Xcode自带的UI视图调试神器吗?

        UIView *tabBarButton = [tabBarItem valueForKey:@"_view"];
         for (UIView *subView in tabBarButton.subviews) {
             if ([subView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
                 return subView;
             }
         }
    

    找到了Badge可以依靠的UIView, 剩下添加Badge的工作就变得容易很多了。

    重写Model中description方法,达到打印对象信息的目的。

    -(NSString *)description
    {
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        uint count;
        objc_property_t *properties = class_copyPropertyList([self class], &count);
        
        for (int i = 0; i<count; i++) {
            objc_property_t property = properties[i];
            NSString *name = @(property_getName(property));
            id value = [self valueForKey:name]?:@"nil";      
           [dictionary setObject:value forKey:name];
        }
        
        free(properties);
        return [NSString stringWithFormat:@"<%@: %p> -- %@",[self class],self,dictionary];
    }
    

    相关文章

      网友评论

          本文标题:RunTime 之其他实践运用

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