美文网首页
runtime运行时之字典模型互转(二)

runtime运行时之字典模型互转(二)

作者: T_Yang | 来源:发表于2017-05-05 14:29 被阅读24次

    上次介绍了runtime自动归档,这次我们来看一下非常常用的-字典转模型/模型转字典。
    很多朋友都会用到MJExtension,它的里面就是用runtime实现了考虑到各种情况的模型字典互转。
    我们这次简单的介绍一下,以最简单的Peeson为例:

    • Person.h
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject <NSCoding>
    @property (nonatomic, copy) NSString *name1;
    @property (nonatomic, copy) NSString *name2;
    @property (nonatomic, copy) NSString *name3;
    @property (nonatomic, copy) NSString *name4;
    @property (nonatomic, copy) NSString *name5;
    @end
    

    上面的person只有五个普通的NSString属性。

    接下来介绍几个方法和变量类型。<objc/runtime.h>中的:

    void objc_msgSend(void /* id self, SEL op, ... */ )这个再熟悉不过了,发送消息的方法,所有的[x xxxx];调用,都会被编译成这个方法调用,值得一说的是在新的Xcode中objc_msgSend() 被默认成没有参数的类型,在括号内传入参数会参数报错,解决方法是要么把Xcode->Build Setting中的

    置为NO,或者就是强转一下。

    SEL sel_registerName(const char *str);传入方法名用来获取该方法,返回值是我们常见的SEL
    objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)这个方法可以看到返回值是一个结构体,看到方法名和参数应该可以了解到是传入改类和一个数量,和上次自动归档Ivar的时候类似,是获取我们@property的属性(name1~name5)
    const char *property_getName(objc_property_t property)很明显,这个方法是获取我们属性的名字。

    方法介绍的差不多,我们来试着实现一下字典转模型。一般我都都是用一个+方法来实现的:

    + (instancetype)objectWithKeyValue:(NSDictionary *)dictionary {
        id obj = [[self alloc] init];
        for (NSString *key in dictionary.allKeys) {
            id value = dictionary[key];
            
            //set方法的名字是setXxxx: 别忘了写冒号
            NSString *methodName = [NSString stringWithFormat:@"set%@%@:", [[key substringToIndex:1] uppercaseString], [key substringFromIndex:1]];
            SEL setMethod = sel_registerName(methodName.UTF8String);
            if ([obj respondsToSelector:setMethod]) {
                ((void (*) (id, SEL, id))objc_msgSend)(obj, setMethod, value);
            }
        }
        return obj;
    }
    

    可以看到,对于很基础的模型,我们并没有用到过多的runtime方法,只是遍历了字典,用key取到了setter方法,最后自行调用setter为模型的属性赋值。
    但是这样的代码只是适合最初级的普通模型,我们开发中会遇到很多的复杂情况,例如模型嵌套,我们就不能用上述的代码进行解析了:
    比如我们person又增加了一个属性Student, 它也是个模型:

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject <NSCoding>
    @property (nonatomic, copy) NSString *name1;
    @property (nonatomic, copy) NSString *name2;
    @property (nonatomic, copy) NSString *name3;
    @property (nonatomic, copy) NSString *name4;
    @property (nonatomic, copy) NSString *name5;
    
    @property (nonatomic, strong) Person *p;
    @end
    

    这个时候就会用到其他的runtime方法

    objc_property_t class_getProperty(Class cls, const char *name)
    

    获取该条name名字的属性结构体。

    objc_property_attribute_t *property_copyAttributeList(objc_property_t property, unsigned int *outCount)
    

    获取该属性结构体的特性结构体。
    这里有点绕,attribute机构体如下:

    typedef struct {
        const char *name;           /**< The name of the attribute */
        const char *value;          /**< The value of the attribute (usually empty) */
    } objc_property_attribute_t;
    

    我们主要用到的是value,结构体本身主要是描述了property属性的特性,如果我们取到的是NSString,value就等于@"NSString",取到的是Person,value就是@"Person"。

    然后重新实现解析方法:

    + (instancetype)objectWithKeyValue:(NSDictionary *)dictionary {
        id obj = [[self alloc] init];
        for (NSString *key in dictionary.allKeys) {
            id value = dictionary[key];
            objc_property_t property = class_getProperty(self, [key UTF8String]);
            unsigned int count = 0;
            //获取属性的特性(结构体指针)
            objc_property_attribute_t *attributeList = property_copyAttributeList(property, &count);
            objc_property_attribute_t attribute = attributeList[0];
            NSString *typeString = [NSString stringWithUTF8String:attribute.value];
            if ([typeString isEqualToString:@"\"Person\""]) {
                value = [self objectWithKeyValue:value];
            }
            
            //set方法的名字是setXxxx: 别忘了写冒号
            NSString *methodName = [NSString stringWithFormat:@"set%@%@:", [[key substringToIndex:1] uppercaseString], [key substringFromIndex:1]];
            SEL setMethod = sel_registerName(methodName.UTF8String);
            if ([obj respondsToSelector:setMethod]) {
                ((void (*) (id, SEL, id))objc_msgSend)(obj, setMethod, value);
            }
            free(attributeList); //记得copy过要释放
        }
        return obj;
    }
    

    这样就简单的实现了模型中包含模型的解析方法,显示取到了property的attribute,然后通多判断attribute的value来判定是不是person类型,如果是的话就继续深层次解析一遍,对于person中有其他模型组合在一起的情况也是一样的,就是同样需要实现其他模型的解析方法。

    以上就实现了字典转模型


    下面是模型转字典

    - (NSDictionary *)keyValueObject {
        unsigned int count = 0;
        objc_property_t *propertyList = class_copyPropertyList([self class], &count);
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        for (int i = 0; i < count; i++) {
            const char *propertyName = property_getName(propertyList[i]);
            //调用get方法
            SEL getMethod = sel_registerName(propertyName);
            
            id value = ((id (*) (id, SEL))objc_msgSend)(self, getMethod);
            if (value) {
                [dict setValue:value forKey:[NSString stringWithUTF8String:propertyName]];
            }
        }
        return dict;
    }
    

    和模型转字典非常的类似,不过说到底也是个逆向的过程,之前字典转模型用到了sel_registerName()获取setter,模型转字典自然就是getter出模型属性值,显示copyproperty获取属性列表,之后用count为次数for循环获取每个属性的Name然后根据name获取getter从而runtime调用getter方法取到属性值放入字典。

    以上便是模型转字典了,虽然没有字典转模型常用,但我们也要知道其过程才行,对于对运行时语言OC的理解和以后的面试都会有帮助的。

    多谢浏览!

    相关文章

      网友评论

          本文标题:runtime运行时之字典模型互转(二)

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