【发布时间】:2015-06-05 14:33:38
【问题描述】:
我需要使用 NSUserDefaults 保存从 jSON 获得的数组,问题是它只保存第一个字符串而不是所有数组。因此,如果数组像 NewYork,London,Rome .. 它只保存 NewYork。我将它用于选择器视图。 这是代码:
编辑 从 JSON 中保存数组:
if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: &error) as? [String:AnyObject] { // dictionary
if let locationsArray = jsonData["locations"] as? [[String:AnyObject]] { // array of dictionaries
for locationDictionary in locationsArray { // we loop in the array of dictionaries
if let location = locationDictionary["location_name"] as? String { // finally, access the dictionary like you were trying to do
// println(location)
var locationSave: Void = save.setObject(location, forKey: "Location")
}
}
}
}
}
请求数组:
var Location = save.objectForKey("Location")!
var pickerviewFields = Location
return pickerviewFields.count
提前致谢!
【问题讨论】:
-
你从哪里得到
location? -
是一个带有数组的变量,我使用 json 从数据库中获取。如果我在控制台中打印变量位置,我可以毫无问题地看到所有位置。所以问题不是 var 位置,而是“位置”变量。
标签: arrays swift nsuserdefaults