首页 文章

带有NSNumber到NSString映射的NSDictionary是非属性列表对象

提问于
浏览
2

以下代码:

[[NSUserDefaults standardUserDefaults] setObject:photoIdToPath forKey:@"photo_id_to_path"];

给我以下错误:

Attempt to set a non-property-list object {
417675729 = "/Users/k06a/Library/Application Support/iPhone Simulator/7.1/Applications/21163736-DF6F-4E79-8196-6A966C81ED1B/Documents/417675729";
} as an NSUserDefaults value for key photo_id_to_path

这是来自Xcode调试控制台的 photoIdToPath 字典内容分析:

(lldb) po photoIdToPath
{
    417675729 = "/Users/k06a/Library/Application Support/iPhone Simulator/7.1/Applications/21163736-DF6F-4E79-8196-6A966C81ED1B/Documents/417675729";
}

(lldb) po [[[photoIdToPath allKeys] lastObject] class]
__NSCFNumber

(lldb) po [[[photoIdToPath allValues] lastObject] class]
NSPathStore2

所以 NSPathStore2NSString 的子类,为什么这个字典不是属性列表?

UPDATE:

这里https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsuserdefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/setObject:forKey:我找到了文字:

value参数只能是属性列表对象:NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary . 对于NSArray和NSDictionary对象,其内容必须是属性列表对象 . 请参阅“属性列表编程指南”中的“什么是属性列表?” .

1 回答

  • 12

    您可以将字典保存为 NSUserDefaults (或将字典作为plist写入文件)的唯一方法是,所有键必须是 NSString 对象,并且所有值必须是有效的plist对象 .

    换句话说,您不能拥有 NSNumber 对象的键 . 如果您需要将字典写入 NSUserDefaults ,请将它们转换为 NSString .

    有关详细信息,请参阅Property List Programming Guide . 特别是 Headers 为What is a Property List?的部分 . 有一个表格显示了使用的XML标签 . 在该表下,您将看到此摘录:

    虽然NSDictionary和CFDictionary对象允许它们的键是任何类型的对象,但如果键不是字符串对象,则集合不是属性列表对象 .

相关问题