一、在模型类中自定义方法来实现,注意:属性名称和字典里面的KEY要和实际数据的属性一样
a、在模型类中的实现
// 模型类 .h文件
@interface Person: NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) UIInteger age;
// 自定义这个方法
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)personWithDict:(NSDictionary *)dict;
@end
// 模型类 .m文件实现
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]){
self.name = dict[@"name"];
self.age = dict[@"age"];
}
return self;
}
+ (instancetype)personWithDict:(NSDictionary *)dict
{
return [ [self alloc] initWithDict:dict];
}b、在获取模型数据类中的实现
Person *p = [Person alloc] initWithDict:dict];(这里直接字典转模型) // Person *p = [Person personWithDict:dict];
二、直接用KVC实现,注意模型属性要和数据的实际属性相同,不然用KVC方法会报错
a、在模型类中的实现
// 模型类 .h文件
@interface Person: NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) UIInteger age;
// 自定义这个方法
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)personWithDict:(NSDictionary *)dict;
@end
// 模型类 .m文件实现
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]){
// self.name = dict[@"name"];
// self.age = dict[@"age"];
[self setValuesForKeysWithDictionary:dict]; (这里实现)
}
return self;
}
+ (instancetype)personWithDict:(NSDictionary *)dict
{
return [ [self alloc] initWithDict:dict];
}b、在获取模型数据类中的实现
1 Person *p = [Person alloc] initWithDict:dict];(这里直接字典转模型) 2 // Person *p = [Person personWithDict:dict];
三、利用封装好的第三方框架实现
如: MJExtension 具体实现看github的介绍
本文出自 “future” 博客,请务必保留此出处http://yuanshui.blog.51cto.com/2097536/1632843
原文地址:http://yuanshui.blog.51cto.com/2097536/1632843