OGeek|极客世界-中国程序员成长平台

标题: ios - [iOS]KVO setValuesForKeysWithDictionary [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:48
标题: ios - [iOS]KVO setValuesForKeysWithDictionary

我正在使用 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";
}

我知道类型应该是“歌曲”而不是歌曲。

当我使用 [model setValue"type"forKey"type"];它不会崩溃。

但我不想用like

[model setValue"type" forKey"type"];

如何解决这个问题?



Best Answer-推荐答案


忘记使用 KVC 并手动编写一个接受 NSDictionaryinit 方法。

然后,您可以决定如何解释字典中的每个值;例如 type 应该是 enum,而不是字符串,imageUrl 应该是 NSURLuuid 应该是 NSUUID 等。

关于ios - [iOS]KVO setValuesForKeysWithDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31289441/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4