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… } }}总结
以上是内存溢出为你收集整理的ios – 如何使用swift将一组对象保存到NSUserDefault?全部内容,希望文章能够帮你解决ios – 如何使用swift将一组对象保存到NSUserDefault?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)