背景:在日常的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











网友评论