gpt4 book ai didi

arrays - 数组的 Swift NSUserDefaults setObject

转载 作者:可可西里 更新时间:2023-11-01 02:21:30 28 4
gpt4 key购买 nike

我需要用 NSUserDefaults 保存一个我从 jSON 获得的数组,问题是它只保存第一个字符串而不是所有数组。因此,如果数组类似于 NewYork、London、Rome .. 它只保存 NewYork。我将它用于选择器 View 。这是代码:

编辑从 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

提前致谢!

最佳答案

只能保存一个NSArray,如果Array是Swift Array,则需要进行转换。另外,NSArray 和 NSDictionary 对象,它们的内容必须是属性列表对象。

以下是转换数组的方法:

var MyArray = ["a", "b", "c"]
var MyNSArray: NSArray

MyNSArray = MyArray as NSArray

println("\(MyNSArray)")

打印:(a,b,c)

我有一个带有一些示例 JSON 的小示例:

    var myJSONString: NSString = "{ \"locations\" : [ { \"location_name\" : \"A\" }, { \"location_name\" : \"B\" }, { \"location_name\" : \"C\" }, { \"location_name\" : \"D\" } ] }"
var urlData: NSData? = NSData()
var error: NSError?
var save = NSUserDefaults.standardUserDefaults()

urlData = myJSONString.dataUsingEncoding(NSUTF8StringEncoding)

if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: &error) as? NSDictionary { // dictionary
if let locationsArray = jsonData["locations"] as? NSArray { // array of dictionaries
for locationDictionary in locationsArray { // we loop in the array of dictionaries
if let location = locationDictionary["location_name"] as? NSString {
println(location)
}
}
NSUserDefaults.standardUserDefaults().setObject(locationsArray, forKey: "locationArray")
}
}

println(save.dictionaryRepresentation())

关于arrays - 数组的 Swift NSUserDefaults setObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30669202/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com