YYModel 源码阅读笔记:
首先调用
1. + (instancetype)modelWithJSON:(id)json;
+ (instancetype)modelWithJSON:(id)json {
//将传进来的源数据转成NSDictionary类型,
//支持NSString,NSData,NSDictionary
NSDictionary *dic = [self _yy_dictionaryWithJSON:json];
// jsos->model
return [self modelWithDictionary:dic];
}
2. + (NSDictionary *)_yy_dictionaryWithJSON:(id)json;
//转换成NSDictionary
+ (NSDictionary *)_yy_dictionaryWithJSON:(id)json {
//json非空判断 (kCFNull为NSNULL的单例)
if (!json || json == (id)kCFNull) return nil;
NSDictionary *dic = nil;
NSData *jsonData = nil;
//如果是字典类型直接返回
if ([json isKindOfClass:[NSDictionary class]]) {
dic = json;
} else if ([json isKindOfClass:[NSString class]]) { //如果是字符串类型,转成NSData类型
jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
} else if ([json isKindOfClass:[NSData class]]) { //如果是data,直接赋值
jsonData = json;
}
if (jsonData) { //将data类型的数据转换成NSDictionary
dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
}
return dic;
}
3.- (BOOL)modelSetWithDictionary:(NSDictionary *)dic;
- (BOOL)modelSetWithDictionary:(NSDictionary *)dic {
if (!dic || dic == (id)kCFNull) return NO; //非空的检查
if (![dic isKindOfClass:[NSDictionary class]]) return NO; //类型的检查
//获取元类model
_YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:object_getClass(self)];
// 没有key->property直接返回
if (modelMeta->_keyMappedCount == 0) return NO;
// 如果重写了此方法,可修改数据源
if (modelMeta->_hasCustomWillTransformFromDictionary) {
dic = [((id<YYModel>)self) modelCustomWillTransformFromDictionary:dic];
if (![dic isKindOfClass:[NSDictionary class]]) return NO;
}
//结构体
ModelSetContext context = {0};
//model的元数据
context.modelMeta = (__bridge void *)(modelMeta);
//model本身
context.model = (__bridge void *)(self);
//model 数据源
context.dictionary = (__bridge void *)(dic);
//CFDictionaryApplyFunction / CFArrayApplyFunction
//会为 dictionary / array 数据中指定范围的每一个元素调用一次指定的方法
//遍历容器类能带来性能提升
//元类model的property个数小于数据源个数
if (modelMeta->_keyMappedCount >= CFDictionaryGetCount((CFDictionaryRef)dic)) {
//基本的json->model : 类似 @{@"name":@"henry"};
CFDictionaryApplyFunction((CFDictionaryRef)dic, ModelSetWithDictionaryFunction, &context);
//如果重写了 modelCustomPropertyMapper 方法,才会有可能调用下面两个方法
if (modelMeta->_keyPathPropertyMetas) {
/**
+ (NSDictionary *)modelCustomPropertyMapper {
return @{@"name" : @"n",
@"page" : @"p",
@"desc" : @"ext.desc",
@"bookID": @[@"id", @"ID", @"book_id"]};
}
*/
//此方法支持的类型 @{@"desc" : @"ext.desc"}
CFArrayApplyFunction((CFArrayRef)modelMeta->_keyPathPropertyMetas,
CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta->_keyPathPropertyMetas)),
ModelSetWithPropertyMetaArrayFunction,
&context);
}
//此方法支持的类型 @{@"bookID": @[@"id", @"ID", @"book_id"]}
if (modelMeta->_multiKeysPropertyMetas) {
CFArrayApplyFunction((CFArrayRef)modelMeta->_multiKeysPropertyMetas,
CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta->_multiKeysPropertyMetas)),
ModelSetWithPropertyMetaArrayFunction,
&context);
}
} else {
//解析全部property
CFArrayApplyFunction((CFArrayRef)modelMeta->_allPropertyMetas,
CFRangeMake(0, modelMeta->_keyMappedCount),
ModelSetWithPropertyMetaArrayFunction,
&context);
}
//检查是否存在此方法,(此方法为默认转换不符合调用的模型对象)
if (modelMeta->_hasCustomTransformFromDictionary) {
return [((id<YYModel>)self) modelCustomTransformFromDictionary:dic];
}
return YES;
}
3.1 [_YYModelMeta metaWithClass:object_getClass(self)]; 初始化方法
/// Returns the cached model class meta
+ (instancetype)metaWithClass:(Class)cls {
if (!cls) return nil;
static CFMutableDictionaryRef cache;
static dispatch_once_t onceToken;
static dispatch_semaphore_t lock;
dispatch_once(&onceToken, ^{
cache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
//创建信号量,只有一个线程访问资源
lock = dispatch_semaphore_create(1);
});
//将信号量的值 -1
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
_YYModelMeta *meta = CFDictionaryGetValue(cache, (__bridge const void *)(cls));
//将信号量的值 +1
dispatch_semaphore_signal(lock);
if (!meta || meta->_classInfo.needUpdate) {
meta = [[_YYModelMeta alloc] initWithClass:cls];
if (meta) {
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
CFDictionarySetValue(cache, (__bridge const void *)(cls), (__bridge const void *)(meta));
dispatch_semaphore_signal(lock);
}
}
return meta;
}
3.2 ModelSetWithDictionaryFunction 基础的dictionary转model
static void ModelSetWithDictionaryFunction(const void *_key, const void *_value, void *_context) {
//获取当前context结构体
ModelSetContext *context = _context;
//context model的元数据
__unsafe_unretained _YYModelMeta *meta = (__bridge _YYModelMeta *)(context->modelMeta);
//元数据的源数据 dictionary
__unsafe_unretained _YYModelPropertyMeta *propertyMeta = [meta->_mapper objectForKey:(__bridge id)(_key)];
//context model(调用者)
__unsafe_unretained id model = (__bridge id)(context->model);
while (propertyMeta) {
//获取到元类型 set方法,给model(调用者)每一个property赋值
if (propertyMeta->_setter) {
ModelSetValueForProperty(model, (__bridge __unsafe_unretained id)_value, propertyMeta);
}
//递归调用,如果下一个meta有多个属性,如果为nil则跳出while循环
propertyMeta = propertyMeta->_next;
};
}
3.3 ModelSetWithPropertyMetaArrayFunction 复杂的模式转model
static void ModelSetWithPropertyMetaArrayFunction(const void *_propertyMeta, void *_context) {
//获取当前context结构体
ModelSetContext *context = _context;
//获取源数据
__unsafe_unretained NSDictionary *dictionary = (__bridge NSDictionary *)(context->dictionary);
//获取元类
__unsafe_unretained _YYModelPropertyMeta *propertyMeta = (__bridge _YYModelPropertyMeta *)(_propertyMeta);
//如果没有实现set方法,直接返回,防止crash
if (!propertyMeta->_setter) return;
id value = nil;
// @{@"bookID": @[@"id", @"ID", @"book_id"]} 这种类型的解析方法
if (propertyMeta->_mappedToKeyArray) {
value = YYValueForMultiKeys(dictionary, propertyMeta->_mappedToKeyArray);
}
// @{@"desc" : @"ext.desc"} 这种类型的解析方法
else if (propertyMeta->_mappedToKeyPath) {
value = YYValueForKeyPath(dictionary, propertyMeta->_mappedToKeyPath);
}
// 默认的解析方式
else {
value = [dictionary objectForKey:propertyMeta->_mappedToKey];
}
//如果存在
if (value) {
__unsafe_unretained id model = (__bridge id)(context->model);
ModelSetValueForProperty(model, value, propertyMeta);
}
}
3.4 ModelSetValueForProperty
ModelSetValueForProperty
没什么好说的,都是调用objc_msgSend方法,为property赋值
// 调用者 方法 参数
((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value);
网友评论