这是一个我定义的地方:
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") } }
这是我如何保存一个地方数组:
var placesArray = [Place] //... func savePlaces() { NSUserDefaults.standardUserDefaults().setObject(placesArray,forKey: "places") println("place saved") }
它没有工作,这是我在控制台上得到的:
Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType')
我是iOS新手,可以帮我吗?
第二版
我找到了一个解决方案来保存数据:
func savePlaces(){ let myData = NSKeyedArchiver.archivedDataWithRootObject(placesArray) NSUserDefaults.standardUserDefaults().setObject(myData,forKey: "places") println("place saved") }
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,存在一个存储/加载过程的问题
任何线索?
解决方法
从
Property List Programming Guide:
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.
您将需要使用NSKeyedArchiver和NSKeyedUnarchiver将对象转换为NSData实例.
例如:
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… } } }