如何使用swift将对象数组保存到NSUserDefault? [英] How to save an array of objects to NSUserDefault with swift?
问题描述
这是一个的地方
我定义了:
class Place: NSObject {
var latitude: Double
var longitude: Double
init(lat: Double, lng: Double, name: String){
self.latitude = lat
self.longitude = lng
}
required init(coder aDecoder: NSCoder) {
self.latitude = aDecoder.decodeDoubleForKey("latitude")
self.longitude = aDecoder.decodeDoubleForKey("longitude")
}
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(latitude, forKey: "latitude")
aCoder.encodeObject(longitude, forKey: "longitude")
}
}
这就是我试图保存数组的地方
s:
This is how I tried to save an array of Place
s:
var placesArray = [Place]
//...
func savePlaces() {
NSUserDefaults.standardUserDefaults().setObject(placesArray, forKey: "places")
println("place saved")
}
它没有工作,这是我在控制台上得到的:
It didn't work, this is what I get on the console:
Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType')
我是iOS新手,你能帮助我吗?
I am new to iOS, could you help me ?
第二版
我找到了保存数据的解决方案:
I found a solution to save the data :
func savePlaces(){
let myData = NSKeyedArchiver.archivedDataWithRootObject(placesArray)
NSUserDefaults.standardUserDefaults().setObject(myData, forKey: "places")
println("place saved")
}
但是在使用此代码加载数据时出现错误:
But I get an error when loading the data with this code :
let placesData = NSUserDefaults.standardUserDefaults().objectForKey("places") as? NSData
if placesData != nil {
placesArray = NSKeyedUnarchiver.unarchiveObjectWithData(placesData!) as [Place]
}
错误是:
[NSKeyedUnarchiver decodeDoubleForKey:]: value for key (latitude) is not a double number'
我很确定我存档了一个Double,保存/加载过程存在问题
I am pretty sure I archived a Double, there is an issue with the saving/loading process
任何线索?
推荐答案
来自属性列表编程指南:
如果属性列表对象是容器(即数组或字典),则其中包含的所有对象也必须是属性列表对象。如果数组或字典包含不是属性列表对象的对象,则无法使用各种属性列表方法和函数保存和还原数据层次结构。
If a property-list object is a container (that is, an array or dictionary), all objects contained within it must also be property-list objects. If an array or dictionary contains objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the various property-list methods and functions.
您需要将对象转换为 NSData
实例使用 NSKeyedArchiver
和 NSKeyedUnarchiver
。
You'll need to convert the object to and from an NSData
instance using NSKeyedArchiver
and NSKeyedUnarchiver
.
例如:
func savePlaces(){
let placesArray = [Place(lat: 123, lng: 123, name: "hi")]
let placesData = NSKeyedArchiver.archivedDataWithRootObject(placesArray)
NSUserDefaults.standardUserDefaults().setObject(placesData, forKey: "places")
}
func loadPlaces(){
let placesData = NSUserDefaults.standardUserDefaults().objectForKey("places") as? NSData
if let placesData = placesData {
let placesArray = NSKeyedUnarchiver.unarchiveObjectWithData(placesData) as? [Place]
if let placesArray = placesArray {
// do something…
}
}
}
这篇关于如何使用swift将对象数组保存到NSUserDefault?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!