【问题标题】:only property-list objects (NSNumber) in NSDictionary but not able to store dict in UserDefaults只有 NSDictionary 中的属性列表对象(NSNumber),但不能在 UserDefaults 中存储 dict
【发布时间】:2013-09-12 13:50:46
【问题描述】:

我有一个 NSDictionary,其中 NSNumbers 作为值和键。这些数字代表应用程序中的某些设置,我想将字典存储在 UserDefaults 中。由于 NSNumbers 是一个属性列表对象,我认为这应该可以工作,但我检索到以下错误:

*** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '{ 2 = 1; }' of class '__NSDictionaryM'. Note that dictionaries and arrays in property lists must also contain only property values.

我使用的(简化的)测试代码是:

NSNumber *one = [NSNumber numberWithInt:1];
NSNumber *two = [NSNumber numberWithInt:2];
NSDictionary *defaultSetting = [[NSDictionary alloc] initWithObjectsAndKeys: one, two, nil];
[[NSUserDefaults standardUserDefaults] setObject:defaultSetting forKey:@"settings"];

为什么这不起作用?我看不出有什么问题?

感谢您的宝贵时间和回复。

【问题讨论】:

    标签: nsdictionary nsuserdefaults nsnumber


    【解决方案1】:

    你的字典必须是这样的:

    NSDictionary *defaultSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                             one, @"one", 
                                                             two, @"two", 
                                                             nil];
    

    【讨论】:

    • 感谢您的回复。在我的情况下,数字“2”是数字“1”的键(它是#defined 值)。但是 UserDefaults 似乎不喜欢将 NSNUmber 作为键值? (我在整个应用程序中成功使用它)。如果我将密钥转换为字符串是有效的.. ?
    • 键必须是 NSString,而不是其他数据类型。
    • 有趣..我检查了 NSDictionary 文档,你确实是正确的。 Apple 规定任何对象都可以是键,但键值编码需要字符串。再次感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多