Swift使用NSUserDefaults在一个循环中保存JSON字符串

时间:2015-07-27 09:37:46

标签: json swift xcode6 nsuserdefaults

今天我想出了如何创建一个for in方法来获得不同的json值..但是现在我无法弄清楚如何将它保存到NSUserDefaults中可能有一个数组。这是我的代码的一部分:

 if let vehicles = jsonData["vehicles"] as? NSDictionary {
                let vehiclesKeys = vehicles.allKeys
                for key in vehiclesKeys {
                    let vehiclenodb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["vechicle_no"]! as! String
                    let modelnodb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["model_no"]! as! String
                    let variantdb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["variant"]! as! String
                    let colordb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["color"]! as! String
                    let datepurchasedb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["date_of_purchase"]! as! String
                    let insurancecompanynamedb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["insurance_company_name"]! as! String
                    let insuranceexpirydatedb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["insurance_expiry_date"]! as! String
                    let fueltypedb = ((jsonData ["vehicles"] as! NSDictionary)["\(key)"]! as! NSDictionary)["fuelType"]! as! String




                    var vehicleno:Void = save.setObject(vehiclenodb, forKey: "VehicleNumberSave")
                    var modelno:Void = save.setObject(modelnodb, forKey: "ModelNumberSave")
                    var variant:Void = save.setObject(variantdb, forKey: "VariantSave")
                    var color:Void = save.setObject(colordb, forKey: "ColorSave")
                    var datepurchase:Void = save.setObject(datepurchasedb, forKey: "DateofPurchaseSave")
                    var insurancecompanyname:Void = save.setObject(insurancecompanynamedb, forKey: "InsuranceCompanySave")
                    var insuranceexpirydate:Void = save.setObject(insuranceexpirydatedb, forKey: "InsuranceExpirySave")
                    var fueltype:Void = save.setObject(fueltypedb, forKey: "FuelTypeSave")

                    save.synchronize()




                }
            }

使用此代码的问题是它保存了最后一个值,我需要保存这两个值,所以就像vehicleno一样= [1vehicle,2vehicle] 我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

你必须在上面创建可变数组for循环,例如

var answersArray : [String]

 answersArray = ["veh1", "veh2", "veh3", "veh4", "veh5", "veh6", "veh7"]

var arrayno = [String]()
for value in answersArray {
     arrayno.append(value)
     println(arrayno)
}

所以最后一个值是

[veh1, veh2, veh3, veh4, veh5, veh6, veh7]

你可以存储整个数组......

答案 1 :(得分:0)

它肯定会保存最后一个值,因为您一次又一次地更新相同的“密钥”。

更好的选择是将空字典添加到其中。

示例:

var myDict: NSDictionary = NSDictionary()

当一个循环完成时,将对象添加到字典中,如:

myDict.setValue("Vehicle1": [arrData])

在“arrData”中,您可以将车辆详细信息保存为

var arrData = NSMutableArray()
dict.addObject(vehicleno)

希望这有帮助!