iOS 数据处理iOS Developer程序员

runtime与字典转模型

2016-03-14  本文已影响543人  小虎哥

设计模型

#import "NSDictionary+PropertyCode.h"

// isKindOfClass:判断是否是当前类或者它的子类

@implementation NSDictionary (PropertyCode)
- (void)createPropertyCode
{
    NSMutableString *strM = [NSMutableString string];
    /*
        解析字典,生成对应属性代码
        1.遍历字典,取出所有key,每个key对应一个属性代码
     
     */
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull value, BOOL * _Nonnull stop) {
        NSLog(@"%@ %@",key,[value class]);
        

        NSString *code = nil;
        if ([value isKindOfClass:[NSString class]]) {
            // NSString
            code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSString *%@;",key];
            
        } else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){
            //    Bool
            code = [NSString stringWithFormat:@"@property (nonatomic ,assign) BOOL %@;",key];
        }else if ([value isKindOfClass:[NSNumber class]]){
            //    NSInteger
            code = [NSString stringWithFormat:@"@property (nonatomic ,assign) NSInteger %@;",key];
        }else if ([value isKindOfClass:[NSArray class]]){
            //    NSArray
            code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSArray *%@;",key];
        }else if ([value isKindOfClass:[NSDictionary class]]){
            //    NSDictionary
            code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSDictionary *%@;",key];
            
        }
        

         // 获取所有key
        [strM appendFormat:@"\n%@\n",code];
       
    }];
    
    NSLog(@"%@",strM);
    
}
@end

字典转模型

方式一:KVC

- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{

}

方式二:Runtime

#import <Foundation/Foundation.h>

@protocol ModelDelegate <NSObject>

@optional
// 提供一个协议,只要准备这个协议的类,都能把数组中的字典转模型
、、用在三级数组转换
+ (NSDictionary *)arrayContainModelClass;

@end
@interface NSObject (Item)

// 字典转模型
+ (instancetype)objectWithDict:(NSDictionary *)dict;

@end
#import "NSObject+Item.h"

#import <objc/message.h>
/*
* 把字典中所有value给模型中属性赋值,
* KVC:遍历字典中所有key,去模型中查找
* Runtime:根据模型中属性名去字典中查找对应value,如果找到就给模型的属性赋值.
*/
@implementation NSObject (Item)
// 字典转模型
+ (instancetype)objectWithDict:(NSDictionary *)dict
{
    // 创建对应模型对象
    id objc = [[self alloc] init];
    
    
    unsigned int count = 0;
    
    // 1.获取成员属性数组
    Ivar *ivarList = class_copyIvarList(self, &count);
    
    // 2.遍历所有的成员属性名,一个一个去字典中取出对应的value给模型属性赋值
    for (int i = 0; i < count; i++) {
        
        // 2.1 获取成员属性
        Ivar ivar = ivarList[i];
        
        // 2.2 获取成员属性名 C -> OC 字符串
       NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        
        // 2.3 _成员属性名 => 字典key
        NSString *key = [ivarName substringFromIndex:1];
        
        // 2.4 去字典中取出对应value给模型属性赋值
        id value = dict[key];
        
        
        // 获取成员属性类型
        NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        
        // 二级转换,字典中还有字典,也需要把对应字典转换成模型
        //
        // 判断下value,是不是字典
        if ([value isKindOfClass:[NSDictionary class]] && ![ivarType containsString:@"NS"]) { //  是字典对象,并且属性名对应类型是自定义类型
            // user User
           
            // 处理类型字符串 @\"User\" -> User
            ivarType = [ivarType stringByReplacingOccurrencesOfString:@"@" withString:@""];
            ivarType = [ivarType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            // 自定义对象,并且值是字典
            // value:user字典 -> User模型
            // 获取模型(user)类对象
            Class modalClass = NSClassFromString(ivarType);
            
            // 字典转模型
            if (modalClass) {
                // 字典转模型 user
                value = [modalClass objectWithDict:value];
            }
            
            // 字典,user
//            NSLog(@"%@",key);
        }
      
        // 三级转换:NSArray中也是字典,把数组中的字典转换成模型.
        // 判断值是否是数组
        if ([value isKindOfClass:[NSArray class]]) {
            // 判断对应类有没有实现字典数组转模型数组的协议
            if ([self respondsToSelector:@selector(arrayContainModelClass)]) {
                
                // 转换成id类型,就能调用任何对象的方法
                id idSelf = self;
                
                // 获取数组中字典对应的模型
                NSString *type =  [idSelf arrayContainModelClass][key];
                
                // 生成模型
                Class classModel = NSClassFromString(type);
                NSMutableArray *arrM = [NSMutableArray array];
                // 遍历字典数组,生成模型数组
                for (NSDictionary *dict in value) {
                    // 字典转模型
                    id model =  [classModel objectWithDict:dict];
                    [arrM addObject:model];
                }
                
                // 把模型数组赋值给value
                value = arrM;
                
            }
        }

        // 2.5 KVC字典转模型
        if (value) {
            
            [objc setValue:value forKey:key];
        }
    }
    

    // 返回对象
    return objc;
    
}
@end
#import <Foundation/Foundation.h>
#import "NSObject+Item.h"
@class User;
@interface Status : NSObject <ModelDelegate>

@property (nonatomic, strong) NSString *source;

@property (nonatomic, assign) int reposts_count;

@property (nonatomic, strong) NSArray *pic_urls;

@property (nonatomic, strong) NSString *created_at;

@property (nonatomic, assign) int attitudes_count;

@property (nonatomic, strong) NSString *idstr;

@property (nonatomic, strong) NSString *text;

@property (nonatomic, assign) int comments_count;

@property (nonatomic, strong) User *user;

@end

#import "Status.h"

@implementation Status
+ (NSDictionary *)arrayContainModelClass
{
    return @{@"pic_urls" : @"Picture"};
}

@end
上一篇下一篇

猜你喜欢

热点阅读