美文网首页
iOS开发—用NSDictionary初始化数据模型(model

iOS开发—用NSDictionary初始化数据模型(model

作者: lei_FY | 来源:发表于2019-01-31 15:45 被阅读0次

背景:在日常的iOS开发的中,从服务器拿到json数据经过处理(如何处理此篇不做详细阐述)之后得大部分情况下得到的是一个包含很业务逻辑数据的额NSDictionary字典,那么一个能通用的,安全的用NSDictionary来初始化model的方法就很重要了。
例如.服务器返回json处理之后是如下的字典

     userName  = @"leifangyou";
     phone = @"110";
     userId = @"5201314";

你可能会对应的这样建立 model

   #import <Foundation/Foundation.h>
   @interface   AccountModel : NSObject
   @property (nonatomic,copy) NSString  *userName;
   @property (nonatomic, copy) NSString  *phone;
   @property (nonatomic, copy) NSString  *userId;
   @end

那么如何优雅的初始化呢, 如下,写一个基类
我是头文件

   #import "LEIBaseInfo.h"
    @interface    LeiSirBaseInfo :NSObject
    + (instancetype) infoWithDictionary:(NSDictionary*)infoDic;
    - (instancetype) initWithDictionary:(NSDictionary*)infoDic;
    @end

我是.m 文件

    @implementation VEXBaseInfo
    + (instancetype) infoWithDictionary:(NSDictionary *)infoDic
    {
        id info = [[self alloc] initWithDictionary:infoDic];
        return info;
    }
    - (instancetype) initWithDictionary:(NSDictionary *)infoDic
    {
        self = [super init];
        if (self)
    {
    [infoDic enumerateKeysAndObjectsUsingBlock:
             ^(id key, id obj, BOOL *stop)
             {
                 id value = obj;
                 if ([obj isKindOfClass:[NSNumber class]])
                 {
                 if (strcmp([obj objCType], @encode(BOOL)) != 0)
                 {
                         @try
                         {
                             value = [NSString stringWithFormat:@"%@",[obj stringValue]];
                         }
                         @catch (NSException * e)
                         {
                             if ([[e name] isEqualToString:NSInvalidArgumentException])
                           {
                                 NSNumber *temp =[NSNumber numberWithBool:[obj boolValue]];
                                 value =  [NSString stringWithFormat:@"%@",[temp stringValue]];
                            }
                         }
                     }
                 }
                 else if([obj isKindOfClass:[NSNull class]])
                 {
                     value = @"";
                 }
                 [self setValue:value forKey:key];
               }];
        }
        return self;
    }
    - (void)setValue:(id)value forUndefinedKey:(NSString *)key
    {

    }

建立了这个基类之后。具体的业务model 继承这个基类

   #import <Foundation/Foundation.h>
   @interface   AccountModel : LEIBaseInfo
   @property (nonatomic,copy) NSString  *userName;
   @property (nonatomic, copy) NSString  *phone;
   @property (nonatomic, copy) NSString  *userId;
   @end

然后,就可以快捷安全的用字典初始化model了
例如

     AccountModel *handSome = [AccountModel infoWithDictionary:dic];
     self.label.text =  handSome.userName;

虽然简单,但是实用!
leifangyou@gmail.com

相关文章

网友评论

      本文标题:iOS开发—用NSDictionary初始化数据模型(model

      本文链接:https://www.haomeiwen.com/subject/pwoksqtx.html