访问__NSDictionaryI数据

时间:2016-02-16 22:44:26

标签: ios objective-c iphone xcode swift

我使用以下代码将字典保存到NSUserDefaults中:

let data = NSKeyedArchiver.archivedDataWithRootObject(self.markerArray)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "pins")

要访问此数据,请使用

let outData = NSUserDefaults.standardUserDefaults().dataForKey("pins")
let dict = NSKeyedUnarchiver.unarchiveObjectWithData(outData!)

打印字典时,我得到了我想要的东西:完整的数据字典(样本):

79 =     {
    address = "Arizona, USA";
    category = nature;
    id = 135;
    lang = "-112.113";
    lat = "36.107";
    name = "Grand Canyon National Park";
    placeId = ChIJFU2bda4SM4cRKSCRyb6pOB8;
    type = "point_of_interest";
};

现在,当我想访问特定条目时,我得到的只是 nil

print(dict!["79"]!["name"]!)

如果有帮助,未归档的字典的类型为 __ NSDictionaryI 。 运行以下代码也会打印 nil

print("dict[79] is of type: \(dict!["79"]!.dynamicType)")

1 个答案:

答案 0 :(得分:2)

您很可能遇到类型问题。为什么79必须是一个字符串?我想它只是一个数字(NSNumber)。

请参阅以下示例:

let dict: NSDictionary = [
    79: "test 1",
   "79": "test 2"
]

print(dict[79]) // prints "test 1"
print(dict["79"]) // prints "test 2"