我对iOS比较陌生,在保存字典并在NSUserDefaults中更新时面临问题...这是我的实现。
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"KEY"]) {
[[[NSUserDefaults standardUserDefaults] objectForKey:@"KEY"] setObject:someString forKey:otherKey];
} else {
[[NSUserDefaults standardUserDefaults] setObject:[self.dictionary setObject:someString forKey:otherKey] forKey:@"KEY"];
}
我最初在userdefaults中检查" KEY,如果该键不存在,我想将字典设置为键的对象" KEY"而下一次控制来到这里,因为" KEY"将存在将字典反对" KEY"并在字典中设置另一个对象。 someString和otherKey来自调用函数。
我得到"向id_Nullable"类型的参数发送void,我知道setObject想要一些对象,它在这里接收无效,但现在该做什么。我迷路了。
我想我在这里缺乏一些基础知识,请帮助别人。谢谢!
答案 0 :(得分:0)
setObject方法返回nil,您尝试在[NSUserDefault standardUserDefaults]中设置。请参阅以下更新的解决方案代码:
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"KEY"]) {
//'objectForKey' returns nullable id and not NSDictionary, so you can't directly treat as dictionary
//[[[NSUserDefaults standardUserDefaults] objectForKey:@"KEY"] setObject:someString forKey:otherKey];
//Change it to below code
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"someString" forKey:@"KEY"];
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"otherKey"];
} else {
//'setObject' method returns nil, which you are trying to set in [NSUserDefault standardUserDefaults]
//[[NSUserDefaults standardUserDefaults] setObject:[self.dictionary setObject:someString forKey:otherKey] forKey:@"KEY"];
[self.dictionary setObject:someString forKey:otherKey];
[[NSUserDefaults standardUserDefaults] setObject:self.dictionary forKey:@"KEY"];
}