YYModel 源码分析:模型设计

本文深入探讨YYModel的模型设计,分析其结构和代码实现,包括属性对应、字典转模型的过程。通过两个实例展示模型的设计思路,详细解释先标记后处理的策略,并给出具体代码实现。
摘要由CSDN通过智能技术生成

前文介绍了 YYModel 怎么字典转模型,

YYModel 源码分析:字典转模型

概述

本文继续探讨,modelMeta,存放模型的属性、和字典的键对应关系的描述文件

结构:

主要使用四个模型:

  • @interface YYClassPropertyInfo : NSObject

对应模型的属性

  • @interface YYClassInfo : NSObject

对应模型的类

包含属性字典,NSDictionary<NSString *, YYClassIvarInfo *>

  • @interface _YYModelPropertyMeta : NSObject

对应模型的属性,及其处理

包含一个成员变量 YYClassPropertyInfo *_info,

把模型取得的属性 YYClassPropertyInfo 及其处理,封装在一起

  • @interface _YYModelMeta : NSObject

对应模型的类,及其处理

包含一个成员变量 YYClassInfo *_classInfo,

把模型取得的类信息 YYClassInfo 及其处理,封装在一起

模型,为什么这么设计

下面,通过两个例子来介绍

例子一, + (NSDictionary *)modelCustomPropertyMapper

模型如下:


@interface Author : NSObject
@property NSString *name;
@property NSString *birthday;
@end

@implementation Author
@end
    
@interface Book : NSObject
@property NSString *name;
@property NSUInteger pages;
@property Author *reporter;

@end

@implementation Book

+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"pages" : @"p",
             @"reporter" : @[@"author",@"writer"]};
}

@end

代码实现

_YYModelMeta : NSObject 的实现中

先标记
  • 对于 [ @"pages" : @"p" ],

通过下面的成员变量,维护一层映射关系

NSDictionary *_mapper;
  • 对于 [ @"reporter" : @[@"author",@"writer"],

通过下面的成员变量,持有记录

NSArray *_multiKeysPropertyMetas;

具体实现

- (instancetype)initWithClass:(Class)cls {

    // ...
    NSMutableDictionary *mapper = [NSMutableDictionary new];
    // ...
    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 删除 @"pages" 对应的
            // allPropertyMetas 删除 @"reporter" 对应的
            [allPropertyMetas removeObjectForKey:propertyName];
            
            if ([mappedToKey isKindOfClass:[NSString class]]) {
                // 处理这个 ,
                // [ @"pages" : @"p" ]
                if (mappedToKey.length == 0) return;
                
                propertyMeta->_mappedToKey = mappedToKey;
                NSArray *keyPath = [mappedToKey componentsSeparatedByString:@"."];
                for (NSString *onePath in keyPath) {
                    if (onePath.length == 0) {
                     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值