Reputation: 668
today i figured out how to create a for in method to get different json value.. but now i can't figure out how to save it to have maybe an Array in NSUserDefaults. This is a part of my code :
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()
}
}
with this code the problem is that it save the last value, i need to save both value so like vehicleno will be like = [1vehicle,2vehicle] how can i do that?
Upvotes: 2
Views: 905
Reputation: 22374
You have to make mutable array above for loop for example
var answersArray : [String]
answersArray = ["veh1", "veh2", "veh3", "veh4", "veh5", "veh6", "veh7"]
var arrayno = [String]()
for value in answersArray {
arrayno.append(value)
println(arrayno)
}
so the last value will be
[veh1, veh2, veh3, veh4, veh5, veh6, veh7]
and you can store whole array....
Upvotes: 2
Reputation: 9540
It will definitely save the last value because you are updating the same "Key" again and again.
The better option is to take empty dictionary add the objects to it.
Example:
var myDict: NSDictionary = NSDictionary()
When the one loop completes, add the object to dictionary like:
myDict.setValue("Vehicle1": [arrData])
In "arrData", you can save your vehicle details as
var arrData = NSMutableArray()
dict.addObject(vehicleno)
Hope this helps!
Upvotes: 0