[iOS]-JSONModel源码学习

参考博客:

JSONModel 源码解析

简介:

JsonModel是用Objective-C写的开源库。它包含了接受发送、解析JSON数据,用JSON数据驱动初始化你的类,还能够检验JSON和嵌套模型等功能。

源码解析:

initWithDictionary:error:方法

我们主要围绕着initWithDictionary:error:这个方法展开,这个方法非常全面,其中作者做了所有的容错和模型的转化。

该方法的流程图如下:
请添加图片描述
这个方法的代码实现是:

//这个方法里包含了作者做到的所有的容错和模型转化
//几个重要的点:
//关联对象kClassPropertiesKey:(用来保存所有属性信息的NSDictionary)
//关联对象kClassRequiredPropertyNamesKey:(用来保存所有属性的名称的NSSet)
//关联对象kMapperObjectKey:(用来保存JSONKeyMapper):自定义的mapper,具体的方法就是用来自定义修改接受数据中的key
//JSONModelClassProperty:封装的jsonmodel的一个属性,它包含了对应属性的名字:(例如 name:gender),类型(例如 type:NSString),是否是JSONModel支持的类型(isStandardJSONType:YES/NO),是否是可变对象(isMutable:YES/NO)等属性。
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
{
    //1. check for nil input检查输入参数是否为nil
    if (!dict) {
        if (err) *err = [JSONModelError errorInputIsNil];
        return nil;
    }

    //invalid input, just create empty instance
    //2. 输入无效的话,只需创建空实例(参数不是nil,但也不是字典)
    if (![dict isKindOfClass:[NSDictionary class]]) {
        if (err) *err = [JSONModelError errorInvalidDataWithMessage:@"Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'."];
        return nil;
    }

    //3. create a class instance创建类实例(初始化)
    self = [self init];
    if (!self) {

        //super init didn't succeed super初始化未成功
        if (err) *err = [JSONModelError errorModelIsInvalid];
        return nil;
    }

    //check incoming data structure
    //检查传入数据结构
    //4. 检查用户定义的模型里的属性集合是否大于传入的字典里的key集合(如果大于,则返回NO)
    if (![self __doesDictionary:dict matchModelWithKeyMapper:self.__keyMapper error:err]) {
        return nil;
    }

    //import the data from a dictionary
    //从字典导入数据
    //5. 核心方法:字典的key与模型的属性的映射
    if (![self __importDictionary:dict withKeyMapper:self.__keyMapper validation:YES error:err]) {
        return nil;
    }

    //run any custom model validation
    //运行任何自定义模型验证
    //6. 可以重写[self validate:err]方法并返回NO,让用户自定义错误并阻拦model的返回
    if (![self validate:err]) {
        return nil;
    }

    //model is valid! yay!
    //7. 型号有效!耶!终于通过了!成功返回model
    return self;
}

(注意上方代码注释中的1. xxx 2.xxx 3.xxx这些方法标号,后续讲解的时候直接使用这些标号表示需要将的地方 )
其中:

  • 方法1-4:都是对错误的发现与处理。
  • 方法5:是真正的mapping。
  • 方法6:是作者给用户自己定义错误的方法,如果复合了用户自己定义的错误,那么即使mapping成功了,也要返回nil。
  • 方法7:成功返回模型对象。

我们先来看一下JSONModel所持有的一些数据:

  • 关联对象kClassPropertiesKey:(用来保存所有属性信息的NSDictionary)
  • 关联对象kClassRequiredPropertyNamesKey:(用来保存所有属性的名称NSSet)
  • 关联对象kMapperObjectKey:(用来保存JSONKeyMapper):自定义的mapper,具体的使用方法在上面的例子中可以看到。
  • JSONModelClassProperty: 封装的jsonmodel的一个属性,它包含了对应属性的名字(name:sex),类型(type:NSString),是否是JSONModel支持的类型(isStandardJSONType:YES/NO),是否是可变对象(isMutable:YES/NO)等属性。

整个代码的执行流程: 首先,在这个模型类的对象被初始化的时候,遍历自身到所有的父类(直到JSONModel为止),获取所有的属性,并将其保存在一个字典里。获取传入字典的所有key,将这些key与保存的所有属性进行匹配。如果匹配成功,则进行kvc赋值。

首先,在load方法里,定义了该框架支持的类型:

//load方法里,定义了该框架支持的类型:
+(void)load
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        // initialize all class static objects,
        // which are common for ALL JSONModel subclasses
        //初始化所有类静态对象,
        //对于所有JSONModel子类都是通用的
        @autoreleasepool {
            //允许(兼容)的JSON类型
            allowedJSONTypes = @[
                [NSString class], [NSNumber class], [NSDecimalNumber class], [NSArray class], [NSDictionary class], [NSNull class], //immutable JSON classes不可变JSON类
                [NSMutableString class], [NSMutableArray class], [NSMutableDictionary class] //mutable JSON classes可变JSON类
            ];
            
            //允许(兼容)的基本数据类型
            allowedPrimitiveTypes = @[
                @"BOOL", @"float", @"int", @"long", @"double", @"short",
                @"unsigned int", @"usigned long", @"long long", @"unsigned long long", @"unsigned short", @"char", @"unsigned char",
                //and some famous aliases
                //还有一些著名的别名
                @"NSInteger", @"NSUInteger",
                @"Block"
            ];
            
            //valueTransformer是值转换器的意思
            valueTransformer = [[JSONValueTransformer alloc] init];
            
            // This is quite strange, but I found the test isSubclassOfClass: (line ~291) to fail if using [JSONModel class].
            // somewhat related: https://stackoverflow.com/questions/6524165/nsclassfromstring-vs-classnamednsstring
            // //; seems to break the unit tests

            // Using NSClassFromString instead of [JSONModel class], as this was breaking unit tests, see below
            //http://stackoverflow.com/questions/21394919/xcode-5-unit-test-seeing-wrong-class
            //这很奇怪,但我发现如果使用[JSONModel class],测试isSubclassOfClass:(第291行)将失败。
            //有些相关:https://stackoverflow.com/questions/6524165/nsclassfromstring-vs-classnamednsstring
            // //; 似乎打破了单元测试
            //使用NSClassFromString而不是[JSONModel class],因为这破坏了单元测试,请参见下文
            //http://stackoverflow.com/questions/21394919/xcode-5-unit-test-seeing-wrong-class
            //总结:在对JSONModel类进行判断isSubclassOfClass:时,后面写的标准类最好用NSClassFromString而不是[JSONModel class]
            //自己的类型
            JSONModelClass = NSClassFromString(NSStringFromClass(self));
        }
    });
}

接着我们看3. 的init方法,看看都实现了什么:

-(id)init
{
    self = [super init];
    if (self) {
        //do initial class setup进行初始类设置
        [self __setup__];
    }
    return self;
}

-(void)__setup__
{
    //if first instance of this model, generate the property list
    //如果是此模型的第一个实例,请生成属性列表(只有第一次实例化的时候,才执行)
    if (!objc_getAssociatedObject(self.class, &kClassPropertiesKey)) {
        //该__inspectProperties方法是该第三方框架的核心方法之一:它的任务是保存了所有需要赋值的属性。用作在将来与传进来的字典进行映射
        [self __inspectProperties];
    }

    //if there's a custom key mapper, store it in the associated object
    //如果有自定义键映射器,请将其存储在关联的对象中(如果存在自定义的mapper,则将它保存在关联对象里面,key是kMapperObjectKey)
    id mapper = [[self class] keyMapper];
    if ( mapper && !objc_getAssociatedObject(self.class, &kMapperObjectKey) ) {
        objc_setAssociatedObject(
                                 self.class,
                                 &kMapperObjectKey,
                                 mapper,
                                 OBJC_ASSOCIATION_RETAIN // This is atomic这是原子的
                                 );
    }
}

需要注意,上方代码中__setup__方法中调用了一个__inspectProperties:方法,这个方法是这个框架的核心方法之一:它的任务是保存了所有需要赋值的属性,用作将来与传进来的字典进行映射。具体代码实现如下:

//该__inspectProperties方法是该第三方框架的核心方法之一:它的任务是保存了所有需要赋值的属性。用作在将来与传进来的字典进行映射
//inspects the class, get's a list of the class properties
//检查类,获取类属性列表
-(void)__inspectProperties
{
    //JMLog(@"Inspect class: %@", [self class]);

    
    //    最终保存所有属性的字典,形式为(例子):
    //    {
    //        age = "@property primitive age (Setters = [])";
    //        friends = "@property NSArray* friends (Standard JSON type, Setters = [])";
    //        gender = "@property NSString* gender (Standard JSON type, Setters = [])";
    //        name = "@property NSString* name (Standard JSON type, Setters = [])";
    //    }
    NSMutableDictionary* propertyIndex = [NSMutableDictionary dictionary];

    //temp variables for the loops
    //循环的温度变量
    //获取当前的类名
    Class class = [self class];
    NSScanner* scanner = nil;
    NSString* propertyType = nil;

    // inspect inherited properties up to the JSONModel class
    //检查继承到JSONModel类的属性
    //循环条件:当class是JSONModel自己的时候不执行
    while (class != [JSONModel class]) {
        //JMLog(@"inspecting: %@", NSStringFromClass(class));
        
        //属性的个数
        unsigned int propertyCount;
        //获得属性列表(所有@property声明的属性)
        objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

        //loop over the class properties
        //循环遍历所有的属性
        for (unsigned int i = 0; i < propertyCount; i++) {
            //JSONModel里的每一个属性,都被封装成一个JSONModelClassProperty对象
            JSONModelClassProperty* p = [[JSONModelClassProperty alloc] init];

            //get property name
            //获得属性名称
            objc_property_t property = properties[i];//获得当前属性
            const char *propertyName = property_getName(property);//name(C字符串)
            p.name = @(propertyName);//propertyNeme:属性名称,例如:name,age,gender

            //JMLog(@"property: %@", p.name);

            //get property attributes
            //获得属性类型
            const char *attrs = property_getAttributes(property);
            NSString* propertyAttributes = @(attrs);
            // T@\"NSString\",C,N,V_name
            // Tq,N,V_age
            // T@\"NSString\",C,N,V_gender
            // T@"NSArray",&,N,V_friends
            NSArray* attributeItems = [propertyAttributes componentsSeparatedByString:@","];

            //ignore read-only properties
            //说明是只读属性,不做任何操作
            if ([attributeItems containsObject:@"R"]) {
                continue; //to next property到下一个属性
            }
            
            //实例化一个scanner(扫描仪,用于查找相关字符串等功能)
            scanner = [NSScanner scannerWithString: propertyAttributes];

            //JMLog(@"attr: %@", [NSString stringWithCString:attrs encoding:NSUTF8StringEncoding]);
            [scanner scanUpToString:@"T" intoString: nil];
            [scanner scanString:@"T" intoString:nil];

            //check if the property is an instance of a class检查属性是否为类的实例
            if ([scanner scanString:@"@\"" intoString: &propertyType]) {
                //属性是一个对象
                [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"\"<"]
                                        intoString:&propertyType];//propertyType -> NSString

                //JMLog(@"type: %@", propertyClassName);
                p.type = NSClassFromString(propertyType);// p.type = @"NSString"
                p.isMutable = ([propertyType rangeOfString:@"Mutable"].location != NSNotFound);//判断是否是可变的对象
                p.isStandardJSONType = [allowedJSONTypes containsObject:p.type];//是否是该框架兼容的类型

                //read through the property protocols
                //通读属性协议
                //存在协议(数组,也就是嵌套模型)
                while ([scanner scanString:@"<" intoString:NULL]) {

                    NSString* protocolName = nil;

                    [scanner scanUpToString:@">" intoString: &protocolName];

                    if ([protocolName isEqualToString:@"Optional"]) {
                        p.isOptional = YES;
                    } else if([protocolName isEqualToString:@"Index"]) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
                        p.isIndex = YES;
#pragma GCC diagnostic pop

                        objc_setAssociatedObject(
                                                 self.class,
                                                 &kIndexPropertyNameKey,
                                                 p.name,
                                                 OBJC_ASSOCIATION_RETAIN // This is atomic这是原子的
                                                 );
                    } else if([protocolName isEqualToString:@"Ignore"]) {
                        p = nil;
                    } else {
                        p.protocol = protocolName;
                    }
                    //到最接近的>为止
                    [scanner scanString:@">" intoString:NULL];
                }

            }
            //check if the property is a structure检查属性是否为结构体
            else if ([scanner scanString:@"{" intoString: &propertyType]) {
                //属性是结构体
                [scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet]
                                    intoString:&propertyType];

                p.isStandardJSONType = NO;
                p.structName = propertyType;

            }
            //the property must be a primitive
            //属性是基本类型
            else {
                //属性是基本类型:Tq、N、V_age
                //the property contains a primitive data type
                [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@","]
                                        intoString:&propertyType];

                //get the full name of the primitive type
                //获取基元类型的全名
                //propertyType:q
                propertyType = valueTransformer.primitivesNames[propertyType];
                //propertyType:lone
                //基本类型数组
                if (![allowedPrimitiveTypes containsObject:propertyType]) {

                    //type not allowed - programmer mistaken -> exception
                    //类型不允许-程序员错误->异常
                    @throw [NSException exceptionWithName:@"JSONModelProperty type not allowed"
                                                   reason:[NSString stringWithFormat:@"Property type of %@.%@ is not supported by JSONModel.", self.class, p.name]
                                                 userInfo:nil];
                }

            }

            NSString *nsPropertyName = @(propertyName);
            //可选的
            if([[self class] propertyIsOptional:nsPropertyName]){
                p.isOptional = YES;
            }
            
            //可忽略的
            if([[self class] propertyIsIgnored:nsPropertyName]){
                p = nil;
            }
            
            //集合类
            Class customClass = [[self class] classForCollectionProperty:nsPropertyName];
            if (customClass) {
                p.protocol = NSStringFromClass(customClass);
            }

            //few cases where JSONModel will ignore properties automatically
            //很少有JSONModel会自动忽略属性的情况
            //忽略block
            if ([propertyType isEqualToString:@"Block"]) {
                p = nil;
            }

            //add the property object to the temp index
            //将属性对象添加到临时索引
            //如果字典里不存在,则添加到属性字典里(终于添加上去了。。。)
            if (p && ![propertyIndex objectForKey:p.name]) {
                [propertyIndex setValue:p forKey:p.name];
            }

            // generate custom setters and getter
            //生成自定义setter和getter
            if (p)
            {
                //name -> Name(大写p的名字属性的前两个字母)
                NSString *name = [p.name stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[p.name substringToIndex:1].uppercaseString];

                // getter
                SEL getter = NSSelectorFromString([NSString stringWithFormat:@"JSONObjectFor%@", name]);

                if ([self respondsToSelector:getter])
                    p.customGetter = getter;

                // setters
                p.customSetters = [NSMutableDictionary new];

                SEL genericSetter = NSSelectorFromString([NSString stringWithFormat:@"set%@WithJSONObject:", name]);

                if ([self respondsToSelector:genericSetter])
                    p.customSetters[@"generic"] = [NSValue valueWithBytes:&genericSetter objCType:@encode(SEL)];

                for (Class type in allowedJSONTypes)
                {
                    NSString *class = NSStringFromClass([JSONValueTransformer classByResolvingClusterClasses:type]);

                    if (p.customSetters[class])
                        continue;

                    SEL setter = NSSelectorFromString([NSString stringWithFormat:@"set%@With%@:", name, class]);

                    if ([self respondsToSelector:setter])
                        p.customSetters[class] = [NSValue valueWithBytes:&setter objCType:@encode(SEL)];
                }
            }
        }
        //释放属性列表
        free(properties);

        //ascend to the super of the class
        //(will do that until it reaches the root class - JSONModel)
        //升到class上的最高级
        //(将这样做,直到它到达根类-JSONModel)再指向自己的父类,直到等于JSONModel才停止
        class = [class superclass];
    }

    //finally store the property index in the static property index
    //最后将属性索引(属性列表)存储在静态属性索引中
    //(最后保存所有当前类,JSONModel的所有的父类的属性)
    objc_setAssociatedObject(
                             self.class,
                             &kClassPropertiesKey,
                             [propertyIndex copy],
                             OBJC_ASSOCIATION_RETAIN // This is atomic这是原子的
                             );
}

这里补充一个细节:

  • 作者用NSScanner来扫描字符串,将从类结构体里拿过来的属性的描述字符串T@\"NSString\",C,N,V_name中扫描出了类型:NSString
  • 作者两次用到了NSSet:当集合里的元素顺序不重要的时候,优先考虑用NSSet

其中有一些值得注意的点:

  1. 作者利用一个while函数,获取当前类和当前类的除JSONModel的所有父类的属性保存在一个字典中。在将来用于和传入的字典进行映射。
  2. 作者用JSONModelClassProperty类封装了JSONModel的每一个属性。这个类有两个重要的属性:一个是name,它是属性的名称(例如gender)。另一个是type,它是属性的类型(例如NSString)。
  3. 作者将属性分为了如下几个类型:
    (1) 对象(不含有协议)。
    (2) 对象(含有协议,属于模型嵌套)。
    (3) 基本数据类型。
    (4) 结构体。

__doesDictionary方法:

接着我们来看一下4. 里面的实现:

//model类里面定义的属性集合是不能大于传入的字典里的key集合的。
//如果存在了用户自定义的mapper,则需要按照用户的定义来进行转换。
//(例如将gender转换为了sex)。
-(BOOL)__doesDictionary:(NSDictionary*)dict matchModelWithKeyMapper:(JSONKeyMapper*)keyMapper error:(NSError**)err
{
    //check if all required properties are present
    //拿到字典里所有的key
    NSArray* incomingKeysArray = [dict allKeys];
    NSMutableSet* requiredProperties = [self __requiredPropertyNames].mutableCopy;
    //从array拿到set
    NSSet* incomingKeys = [NSSet setWithArray: incomingKeysArray];

    //transform the key names, if necessary
    //如有必要,变换键名称
    //如果用户自定义了mapper,则进行转换
    if (keyMapper || globalKeyMapper) {

        NSMutableSet* transformedIncomingKeys = [NSMutableSet setWithCapacity: requiredProperties.count];
        NSString* transformedName = nil;

        //loop over the required properties list
        //在所需属性列表上循环
        //遍历需要转换的属性列表
        for (JSONModelClassProperty* property in [self __properties__]) {
            //被转换成的属性名称(例如)gender(模型内) -> sex(字典内)
            transformedName = (keyMapper||globalKeyMapper) ? [self __mapString:property.name withKeyMapper:keyMapper] : property.name;

            //check if exists and if so, add to incoming keys
            //检查是否存在,如果存在,则添加到传入密钥
            //(例如)拿到sex以后,查看传入的字典里是否有sex对应的值
            id value;
            @try {
                value = [dict valueForKeyPath:transformedName];
            }
            @catch (NSException *exception) {
                value = dict[transformedName];
            }

            if (value) {
                [transformedIncomingKeys addObject: property.name];
            }
        }

        //overwrite the raw incoming list with the mapped key names
        //用映射的键名称覆盖原始传入列表
        incomingKeys = transformedIncomingKeys;
    }

    //check for missing input keys
    //检查是否缺少输入键
    //查看当前的model的属性的集合是否大于传入的属性集合,如果是,则返回错误
    //也就是说模型类里的属性是不能多于传入字典里的key的,例如:
    if (![requiredProperties isSubsetOfSet:incomingKeys]) {

        //get a list of the missing properties
        //获取缺失属性的列表(获取多出来的属性)
        [requiredProperties minusSet:incomingKeys];

        //not all required properties are in - invalid input
        //并非所有必需的属性都在 in - 输入无效
        JMLog(@"Incoming data was invalid [%@ initWithDictionary:]. Keys missing: %@", self.class, requiredProperties);

        if (err) *err = [JSONModelError errorInvalidDataWithMissingKeys:requiredProperties];
        return NO;
    }

    //not needed anymore
    //不再需要了,释放掉
    incomingKeys= nil;
    requiredProperties= nil;

    return YES;
}

这里需要注意的是:

  1. model类里面定义的属性集合是不能大于传入的字典里的key集合的。(我们所写的接受数据的属性的数量需要小于等于传入的字典的key集合)
  2. 如果存在了用户自定义的mapper,则需要按照用户的定义来进行转换。
    (本例是将gender转换为了sex)。

__importDictionary:方法:

我们最后来看一下本框架的第二个核心代码(上方的方法5. ),就是真正从字典里获取值并赋值给当前模型对象的实现:

//作者在最后给属性赋值的时候使用的是kvc的setValue:ForKey:的方法。
//作者判断了模型里的属性的类型是否是JSONModel的子类,可见作者的考虑是非常周全的。
//整个框架看下来,有很多的地方涉及到了错误判断,作者将将错误类型单独抽出一个类(JSONModelError),里面支持的错误类型很多,可以侧面反应作者思维之缜密。而且这个做法也可以在我们写自己的框架或者项目中使用。
//从字典里获取值并赋给当前模型对象
-(BOOL)__importDictionary:(NSDictionary*)dict withKeyMapper:(JSONKeyMapper*)keyMapper validation:(BOOL)validation error:(NSError**)err
{
    //loop over the incoming keys and set self's properties
    //遍历保存的所有属性的字典
    for (JSONModelClassProperty* property in [self __properties__]) {

        //convert key name to model keys, if a mapper is provided
        //将属性的名称(若有改动就拿改后的名称)拿过来,作为key,用这个key来查找传进来的字典里对应的值
        NSString* jsonKeyPath = (keyMapper||globalKeyMapper) ? [self __mapString:property.name withKeyMapper:keyMapper] : property.name;
        //JMLog(@"keyPath: %@", jsonKeyPath);

        //general check for data type compliance
        //用来保存从字典里获取的值
        id jsonValue;
        @try {
            jsonValue = [dict valueForKeyPath: jsonKeyPath];
        }
        @catch (NSException *exception) {
            jsonValue = dict[jsonKeyPath];
        }

        //check for Optional properties
        //检查可选属性
        //字典不存在对应的key
        if (isNull(jsonValue)) {
            //skip this property, continue with next property
            //跳过此属性,继续下一个属性
            //如果这个key是可以不存在的
            if (property.isOptional || !validation) continue;
            //如果这个key是必须有的,则返回错误
            if (err) {
                //null value for required property
                //所需属性的值为null
                NSString* msg = [NSString stringWithFormat:@"Value of required model key %@ is null", property.name];
                JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg];
                *err = [dataErr errorByPrependingKeyPathComponent:property.name];
            }
            return NO;
        }
        //获取,取到的值的类型
        Class jsonValueClass = [jsonValue class];
        BOOL isValueOfAllowedType = NO;
        //查看是否是本框架兼容的属性类型
        for (Class allowedType in allowedJSONTypes) {
            if ( [jsonValueClass isSubclassOfClass: allowedType] ) {
                isValueOfAllowedType = YES;
                break;
            }
        }
        
        //如果不兼容,则返回NO,mapping失败,抛出错误
        if (isValueOfAllowedType==NO) {
            //type not allowed
            JMLog(@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass));

            if (err) {
                NSString* msg = [NSString stringWithFormat:@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass)];
                JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg];
                *err = [dataErr errorByPrependingKeyPathComponent:property.name];
            }
            return NO;
        }

        //check if there's matching property in the model
        //检查模型中是否有匹配的属性
        //如果是兼容的类型:
        if (property) {

            // check for custom setter, than the model doesn't need to do any guessing
            // how to read the property's value from JSON
            //检查自定义setter,则模型不需要进行任何猜测(查看是否有自定义setter,并设置)
            //如何从JSON读取属性值
            if ([self __customSetValue:jsonValue forProperty:property]) {
                //skip to next JSON key
                //跳到下一个JSON键
                continue;
            };

            // 0) handle primitives
            //0)句柄原语
            //基本类型
            if (property.type == nil && property.structName==nil) {

                //generic setter
                //通用setter
                //kvc赋值
                if (jsonValue != [self valueForKey:property.name]) {
                    [self setValue:jsonValue forKey: property.name];
                }

                //skip directly to the next key
                //直接跳到下一个键
                continue;
            }

            // 0.5) handle nils
            //如果传来的值是空,即使当前的属性对应的值不是空,也要将空值赋给它
            if (isNull(jsonValue)) {
                if ([self valueForKey:property.name] != nil) {
                    [self setValue:nil forKey: property.name];
                }
                continue;
            }


            // 1) check if property is itself a JSONModel
            //检查属性本身是否是jsonmodel类型
            if ([self __isJSONModelSubClass:property.type]) {

                //initialize the property's model, store it
                //初始化属性的模型,并将其存储
                //通过自身的转模型方法,获取对应的值
                JSONModelError* initErr = nil;
                id value = [[property.type alloc] initWithDictionary: jsonValue error:&initErr];

                if (!value) {
                    //skip this property, continue with next property
                    //跳过此属性,继续下一个属性(如果该属性不是必须的,则略过)
                    if (property.isOptional || !validation) continue;

                    // Propagate the error, including the property name as the key-path component
                    //传播错误,包括将属性名称作为密钥路径组件(如果该属性是必须的,则返回错误)
                    if((err != nil) && (initErr != nil))
                    {
                        *err = [initErr errorByPrependingKeyPathComponent:property.name];
                    }
                    return NO;
                }
                //当前的属性值与value不同时,则赋值
                if (![value isEqual:[self valueForKey:property.name]]) {
                    [self setValue:value forKey: property.name];
                }

                //for clarity, does the same without continue
                //为清楚起见,不继续执行相同操作
                continue;

            } else {

                // 2) check if there's a protocol to the property
                //  ) might or not be the case there's a built in transform for it
                //2)检查是否有协议
                //)可能是,也可能不是,它有一个内置的转换
                if (property.protocol) {

                    //JMLog(@"proto: %@", p.protocol);
                    //转化为数组,这个数组就是例子中的friends属性
                    jsonValue = [self __transform:jsonValue forProperty:property error:err];
                    if (!jsonValue) {
                        if ((err != nil) && (*err == nil)) {
                            NSString* msg = [NSString stringWithFormat:@"Failed to transform value, but no error was set during transformation. (%@)", property];
                            JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg];
                            *err = [dataErr errorByPrependingKeyPathComponent:property.name];
                        }
                        return NO;
                    }
                }

                // 3.1) handle matching standard JSON types
                //3.1)句柄匹配标准JSON类型
                //对象类型
                if (property.isStandardJSONType && [jsonValue isKindOfClass: property.type]) {

                    //mutable properties
                    //可变类型的属性
                    if (property.isMutable) {
                        jsonValue = [jsonValue mutableCopy];
                    }

                    //set the property value
                    //为属性赋值
                    if (![jsonValue isEqual:[self valueForKey:property.name]]) {
                        [self setValue:jsonValue forKey: property.name];
                    }
                    continue;
                }

                // 3.3) handle values to transform
                //3.3)处理要转换的值
                //当前的值的类型与对应的属性的类型不一样的时候,需要查看用户是否自定义了转换器(例如从NSSet到NSArray转换:-(NSSet *)NSSetFromNSArray:(NSArray *)array)
                if (
                    (![jsonValue isKindOfClass:property.type] && !isNull(jsonValue))
                    ||
                    //the property is mutable
                    //属性是可变的
                    property.isMutable
                    ||
                    //custom struct property
                    //自定义结构属性
                    property.structName
                    ) {

                    // searched around the web how to do this better
                    // but did not find any solution, maybe that's the best idea? (hardly)
                    //在网上搜索如何更好地做到这一点
                    //但是没有找到任何解决方案,也许这是最好的主意?(几乎没有)
                    Class sourceClass = [JSONValueTransformer classByResolvingClusterClasses:[jsonValue class]];

                    //JMLog(@"to type: [%@] from type: [%@] transformer: [%@]", p.type, sourceClass, selectorName);

                    //build a method selector for the property and json object classes
                    //为属性和json对象类构建方法选择器
                    NSString* selectorName = [NSString stringWithFormat:@"%@From%@:",
                                              (property.structName? property.structName : property.type), //target name目标名
                                              sourceClass]; //source name源名称
                    SEL selector = NSSelectorFromString(selectorName);

                    //check for custom transformer
                    //查看自定义的转换器是否存在
                    BOOL foundCustomTransformer = NO;
                    if ([valueTransformer respondsToSelector:selector]) {
                        foundCustomTransformer = YES;
                    } else {
                        //try for hidden custom transformer
                        //尝试隐藏自定义转换器
                        selectorName = [NSString stringWithFormat:@"__%@",selectorName];
                        selector = NSSelectorFromString(selectorName);
                        if ([valueTransformer respondsToSelector:selector]) {
                            foundCustomTransformer = YES;
                        }
                    }

                    //check if there's a transformer with that name
                    //检查是否有同名变压器
                    //如果存在自定义转换器,则进行转换
                    if (foundCustomTransformer) {
                        IMP imp = [valueTransformer methodForSelector:selector];
                        id (*func)(id, SEL, id) = (void *)imp;
                        jsonValue = func(valueTransformer, selector, jsonValue);

                        if (![jsonValue isEqual:[self valueForKey:property.name]])
                            [self setValue:jsonValue forKey:property.name];
                    } else {
                        //如果没有自定义转换器,返回错误
                        if (err) {
                            NSString* msg = [NSString stringWithFormat:@"%@ type not supported for %@.%@", property.type, [self class], property.name];
                            JSONModelError* dataErr = [JSONModelError errorInvalidDataWithTypeMismatch:msg];
                            *err = [dataErr errorByPrependingKeyPathComponent:property.name];
                        }
                        return NO;
                    }
                } else {
                    // 3.4) handle "all other" cases (if any)
                    //3.4)处理“所有其他”情况(如有)
                    if (![jsonValue isEqual:[self valueForKey:property.name]])
                        [self setValue:jsonValue forKey:property.name];
                }
            }
        }
    }

    return YES;
}

这里值得注意的是:

  • 作者在最后给属性赋值的时候使用的是kvc的setValue:ForKey:的方法。
  • 作者判断了模型里的属性的类型是否是JSONModel的子类,可以看到作者的考虑是非常周全的。
  • 整个框架看下来,有很多的地方涉及到了错误判断,作者将将错误类型单独抽出一个类(JSONModelError),里面支持的错误类型很多,体现了作者思维的缜密。而且这个做法也可以在我们写自己的框架或者项目中使用。

错误判断的一个例子:

//JSONModelError.m
+(id)errorInvalidDataWithMessage:(NSString*)message
{
    message = [NSString stringWithFormat:@"Invalid JSON data: %@", message];
    return [JSONModelError errorWithDomain:JSONModelErrorDomain
                                      code:kJSONModelErrorInvalidData
                                  userInfo:@{NSLocalizedDescriptionKey:message}];
}

以上就是我们全部的JSONModel源码的分析了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值