我正在使用setValuesForKeysWithDictionary填充我的模型对象。模型对象定义为
@interface CommonModel : NSObject
@property (nonatomic,copy)NSString *imageUrl;
@property (nonatomic,copy)NSString *name;
@property (nonatomic,copy)NSString *uuid;
@property (nonatomic,strong)MetaDataModel *metaData;
@property (nonatomic,copy)NSString *type;
@property (nonatomic,copy)NSString *age;
@end我初始化这个类,如下所示
CommonModel *model = [[CommonModel alloc] init];
[model setValuesForKeysWithDictionary:dic];dic来自服务器数据,如
{
category = random;
created = 1436348796510;
duration = 259;
metadata = {
path = "/songs/396677ea-2556-11e5-afe1-033c8b2070b7";
};
modified = 1436348796510;
name = "\U6ce1\U6cab";
type = song;
url = "http://www.devinzhao.com/pomo.mp3";
uuid = "396677ea-2556-11e5-afe1-033c8b2070b7";
}我知道类型应该是“歌”而不是歌。
当我使用模型setValue:@"type“forKey:@”type“时,它不会崩溃。
但我不想用like
[model setValue:@"type" forKey:@"type"];如何解决这个问题?
发布于 2015-07-08 18:07:50
忘记使用KVC,手动编写一个接受NSDictionary的init方法。
然后,您可以决定如何解释字典中的每个值;例如,type应该是enum,而不是字符串,imageUrl应该是NSURL,uuid应该是NSUUID,等等。
发布于 2015-07-08 18:28:19
也许这对你有帮助
CommonModel *model = [[CommonModel alloc] init];
[dic setValue:[NSString stringWithFormat:@"%@",dic[@"type"]] forKey:@"type"];
[model setValuesForKeysWithDictionary:dic];https://stackoverflow.com/questions/31289441
复制相似问题