YYModel源码阅读(1)

最近项目进入空闲期,把YYModel主要的方法重新打了一遍,希望能够帮助自己理解。写下此文,也是做个记录。

首先看第一个方法,我们从YYModelExample.m文件里面可以看到


static void SimpleObjectExample() {

YYBook *book = [YYBook modelWithJSON:@"    \

{                                          \

\"name\": \"Harry Potter\",              \

\"pages\": 512,                          \

\"publishDate\": \"2010-01-01\"          \

}"];

NSString *bookJSON = [book modelToJSONString];

NSLog(@"Book: %@", bookJSON);

}

modelWithJSON:把JSON字符串映射到对应的Model里面

我们点进去看看接下来走的方法.


+ (instancetype)modelWithJSON:(id)json {

NSDictionary*dic = [self _yy_dictionaryWithJSON:json];

return[self modelWithDictionary:dic];

}

其中_yy_dictionaryWithJSON是通过[NSJSONSerialization JSONObjectWithData:option:error]把JSON对象转换NSDictionary对象,接下来重头戏来了,modelWithDictionary:


+ (instancetype)modelWithDictionary:(NSDictionary*)dictionary {

if(!dictionary || dictionary == (id)kCFNull) return nil;

if(![dictionaryisKindOfClass:[NSDictionaryclass]]) return nil;

Classcls = [self class];

_YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:cls];

NSLog(@"modelMeta : %@",modelMeta);

if (modelMeta->_hasCustomClassFromDictionary) {

cls = [cls modelCustomClassForDictionary:dictionary] ?: cls;

}

NSObject*one = [cls new];

if ([one modelSetWithDictionary:dictionary]) return one;

return nil;

}

其中YYModel设计一个这样的YYmodelMeta 这样的来获取当前类的一些信息。


@interface_YYModelMeta :NSObject{

@package

YYClassInfo*_classInfo;

NSDictionary*_mapper;// json key 和 property Meta 的映射关系字典

NSArray*_allPropertyMetas;// 所有属性的propertyMeta

NSArray*_keyPathPropertyMetas;// 映射jsonkeyPath 的PropertyMetas

NSArray*_multiKeysPropertyMetas;// 映射多个jsonKey的propertyMeta

NSUInteger_keyMappedCount;//需要映射的属性的总数

YYEncodingNSType_nsType;/// Model对应的Foundation class类型

//是否实现了自定义的映射关系

BOOL_hasCustomWillTransformFromDictionary;

BOOL_hasCustomTransformFromDictionary;

BOOL_hasCustomTransformToDictionary;

BOOL_hasCustomClassFromDictionary;

}

其中YYClassInfo其实是一个复合类,其中里面包含了类的成员变量ivar,类的方法method,类的属性property。作者把三个分别封装成类,更好的被外部捕捉,提高运行效率。

我们接下来先解析这个类YYClassInfo

你可能感兴趣的:(YYModel源码阅读(1))