iOS源码解析iOS 开发 程序员

YYModel学习笔记(二)

2016-12-19  本文已影响112人  GiantAxe77

前言

_YYModelMeta

/// A class info in object model.
@interface _YYModelMeta : NSObject {
    @package

    // 抽象的类信息
    YYClassInfo *_classInfo;

    /// Key:mapped key and key path, Value:_YYModelPropertyMeta.
    // 映射字典
    NSDictionary *_mapper;

    /// Array<_YYModelPropertyMeta>, all property meta of this model.
   // 包含该类和该类的所有父类 直到 NSObject/NSProxy为止的所有属性抽象类NSArray<_YYModelPropertyMeta>
    NSArray *_allPropertyMetas;

    /// Array<_YYModelPropertyMeta>, property meta which is mapped to a key path.
    // 包含 映射为keypath 的 NSArray<_YYModelPropertyMeta>
    NSArray *_keyPathPropertyMetas;

    /// Array<_YYModelPropertyMeta>, property meta which is mapped to multi keys.
    // @{@"userID" : @[@"ID",@"id",@"user.id"] 类似这样映射,包含有数组映射的NSArray<_YYModelPropertyMeta>
    NSArray *_multiKeysPropertyMetas;

    /// The number of mapped key (and key path), same to _mapper.count.
    NSUInteger _keyMappedCount;

    /// Model class type.
    YYEncodingNSType _nsType;
    
    BOOL _hasCustomWillTransformFromDictionary;
    BOOL _hasCustomTransformFromDictionary;
    BOOL _hasCustomTransformToDictionary;
    BOOL _hasCustomClassFromDictionary;
}
@end
@implementation _YYModelMeta
- (instancetype)initWithClass:(Class)cls {

    // 根据 类 生成 抽象的ClassInfo 类
    YYClassInfo *classInfo = [YYClassInfo classInfoWithClass:cls];
    if (!classInfo) return nil;
    self = [super init];
    
    // Get black list
    // 黑名单,在转换过程中会忽略黑名单中属性
    NSSet *blacklist = nil;
    if ([cls respondsToSelector:@selector(modelPropertyBlacklist)]) {
        NSArray *properties = [(id<YYModel>)cls modelPropertyBlacklist];
        if (properties) {
            blacklist = [NSSet setWithArray:properties];
        }
    }
    
    // Get white list
    // 获取白名单,转换过程中不在其内的属性, 不做处理.
    NSSet *whitelist = nil;
    if ([cls respondsToSelector:@selector(modelPropertyWhitelist)]) {
        NSArray *properties = [(id<YYModel>)cls modelPropertyWhitelist];
        if (properties) {
            whitelist = [NSSet setWithArray:properties];
        }
    }
    
    /*

      + (NSDictionary *)modelContainerPropertyGenericClass {
                return @{
                         @"simZeroHoldVos" : [DDFSimZeroHoldModel class]
                         };
        }

     用下面的转换得到:
       @{
          @"simZeroHoldVos" : @"DDFSimZeroHoldModel"
         }
     */
    // Get container property's generic class
    // 获取容器内部定制的类型的字典
    NSDictionary *genericMapper = nil;
    if ([cls respondsToSelector:@selector(modelContainerPropertyGenericClass)]) {
        genericMapper = [(id<YYModel>)cls modelContainerPropertyGenericClass];
        if (genericMapper) {
            NSMutableDictionary *tmp = [NSMutableDictionary new];
            [genericMapper enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                if (![key isKindOfClass:[NSString class]]) return;
                Class meta = object_getClass(obj);
                if (!meta) return;
                if (class_isMetaClass(meta)) {
                    tmp[key] = obj;
                } else if ([obj isKindOfClass:[NSString class]]) {
                    Class cls = NSClassFromString(obj);
                    if (cls) {
                        tmp[key] = cls;
                    }
                }
            }];
            genericMapper = tmp;
        }
    }
    
    // Create all property metas.
    // 获取 所有的属性
    NSMutableDictionary *allPropertyMetas = [NSMutableDictionary new];
    YYClassInfo *curClassInfo = classInfo;

    // 向上层遍历类,直到父类为空为止,目的是获取所有的属性
    while (curClassInfo && curClassInfo.superCls != nil) { // recursive parse super class, but ignore root class (NSObject/NSProxy)
        for (YYClassPropertyInfo *propertyInfo in curClassInfo.propertyInfos.allValues) {
            if (!propertyInfo.name) continue;
            // 在黑名单的 忽略
            if (blacklist && [blacklist containsObject:propertyInfo.name]) continue;
            // 不在白名单中的 忽略
            if (whitelist && ![whitelist containsObject:propertyInfo.name]) continue;
            // 创建对该属性的抽象类 其中 genericMapper[propertyInfo.name] 代表容器内指定的类
            _YYModelPropertyMeta *meta = [_YYModelPropertyMeta metaWithClassInfo:classInfo
                                                                    propertyInfo:propertyInfo
                                                                         generic:genericMapper[propertyInfo.name]];
            if (!meta || !meta->_name) continue;
            if (!meta->_getter || !meta->_setter) continue;
            // 如果字典中存在 忽略
            if (allPropertyMetas[meta->_name]) continue;
            allPropertyMetas[meta->_name] = meta;
        }
        // 把当前类的父类赋值给 当前类
        curClassInfo = curClassInfo.superClassInfo;
    }
    // 给当前类的属性 _allPropertyMetas 赋值
    if (allPropertyMetas.count) _allPropertyMetas = allPropertyMetas.allValues.copy;
    
    // create mapper
    NSMutableDictionary *mapper = [NSMutableDictionary new];
    NSMutableArray *keyPathPropertyMetas = [NSMutableArray new];
    NSMutableArray *multiKeysPropertyMetas = [NSMutableArray new];
    
    // 如果实现了 modelCustomPropertyMapper方法
    if ([cls respondsToSelector:@selector(modelCustomPropertyMapper)]) {
        // 获取自定义的字典
        NSDictionary *customMapper = [(id <YYModel>)cls modelCustomPropertyMapper];
        // 遍历字典
        [customMapper enumerateKeysAndObjectsUsingBlock:^(NSString *propertyName, NSString *mappedToKey, BOOL *stop) {
            // 根据名字 在 全部属性字典中取出与之相对应的属性抽象类
            _YYModelPropertyMeta *propertyMeta = allPropertyMetas[propertyName];
            // 不存在则返回
            if (!propertyMeta) return;
            // 如果存在,用完后删除,下次遍历进来速度就会提升
            [allPropertyMetas removeObjectForKey:propertyName];
            
            if ([mappedToKey isKindOfClass:[NSString class]]) {
                if (mappedToKey.length == 0) return;
                // 给抽象的 _mappedToKey赋值 标示要被映射的名称
                propertyMeta->_mappedToKey = mappedToKey;
                NSArray *keyPath = [mappedToKey componentsSeparatedByString:@"."];
                // 遍历keyPath数组,若存在空字符就删除
                for (NSString *onePath in keyPath) {
                    if (onePath.length == 0) {
                        NSMutableArray *tmp = keyPath.mutableCopy;
                        [tmp removeObject:@""];
                        keyPath = tmp;
                        break;
                    }
                }
                // 若keyPath个数大于1,比如@"user.uid"
                if (keyPath.count > 1) {
                    propertyMeta->_mappedToKeyPath = keyPath;
                    [keyPathPropertyMetas addObject:propertyMeta];
                }
                // 将next指针指向下一个映射
                propertyMeta->_next = mapper[mappedToKey] ?: nil;
                // 将每一个自定义映射字典的value包装成 _YYModelPropertyMeta 类
                mapper[mappedToKey] = propertyMeta;
                
            } else if ([mappedToKey isKindOfClass:[NSArray class]]) {
                
                NSMutableArray *mappedToKeyArray = [NSMutableArray new];
                for (NSString *oneKey in ((NSArray *)mappedToKey)) {
                    if (![oneKey isKindOfClass:[NSString class]]) continue;
                    if (oneKey.length == 0) continue;
                    // 如果映射的是数组,就保存数组,否则保存字符串
                    NSArray *keyPath = [oneKey componentsSeparatedByString:@"."];
                    if (keyPath.count > 1) {
                        [mappedToKeyArray addObject:keyPath];
                    } else {
                        [mappedToKeyArray addObject:oneKey];
                    }
                    // 若_mappedToKey不存在,则进来赋值保存
                    if (!propertyMeta->_mappedToKey) {
                        propertyMeta->_mappedToKey = oneKey;
                        propertyMeta->_mappedToKeyPath = keyPath.count > 1 ? keyPath : nil;
                    }
                }
                if (!propertyMeta->_mappedToKey) return;
                
                propertyMeta->_mappedToKeyArray = mappedToKeyArray;
                [multiKeysPropertyMetas addObject:propertyMeta];
                
                propertyMeta->_next = mapper[mappedToKey] ?: nil;
                mapper[mappedToKey] = propertyMeta;
            }
        }];
    }
    
    [allPropertyMetas enumerateKeysAndObjectsUsingBlock:^(NSString *name, _YYModelPropertyMeta *propertyMeta, BOOL *stop) {
        propertyMeta->_mappedToKey = name;
        propertyMeta->_next = mapper[name] ?: nil;
        mapper[name] = propertyMeta;
    }];
    
    if (mapper.count) _mapper = mapper;
    if (keyPathPropertyMetas) _keyPathPropertyMetas = keyPathPropertyMetas;
    if (multiKeysPropertyMetas) _multiKeysPropertyMetas = multiKeysPropertyMetas;
    
    _classInfo = classInfo;
    _keyMappedCount = _allPropertyMetas.count;
    _nsType = YYClassGetNSType(cls);
    _hasCustomWillTransformFromDictionary = ([cls instancesRespondToSelector:@selector(modelCustomWillTransformFromDictionary:)]);
    _hasCustomTransformFromDictionary = ([cls instancesRespondToSelector:@selector(modelCustomTransformFromDictionary:)]);
    _hasCustomTransformToDictionary = ([cls instancesRespondToSelector:@selector(modelCustomTransformToDictionary:)]);
    _hasCustomClassFromDictionary = ([cls respondsToSelector:@selector(modelCustomClassForDictionary:)]);
    
    return self;
}

这里补充下小知识👇

CFDictionaryCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks);

第一个参数 : CFAllocatorRef类型,为新字典分配内存。通过NULLkCFAllocatorDefault使用当前默认的分配器
第二个参数 : CFIndex类型, 键值对数目. 传入0的话不限制键值对大小数目.
第三个参数 : CFDictionaryKeyCallBacks类型, 键的回调.
第四个参数 : CFDictionaryValueCallBacks类型, 值得回调

在缓存中读取抽象类

/// 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);
    });
    dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
    _YYModelMeta *meta = CFDictionaryGetValue(cache, (__bridge const void *)(cls));
    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;
}

这里总结_YYModelMeta的实现思路:

上一篇 下一篇

猜你喜欢

热点阅读