我有一个简单的函数,我将一个对象保存到用户默认值,以便以后加载它,它看起来像这样:
func saveGame() { // hero is an instance of the class Hero,subclassed from SKSpriteNode UserDefaults.standard.set(hero,forKey: HeroObjectKey) }
我收到错误:
2017-03-13 21:15:33.124271 Castle[5405:5208658] [User Defaults] Attempt to set a non-property-list object name:’hero’ texture:[ ‘hero1.ico’ (32 x 32)] position:{0,0} scale:{1.00,1.00} size:{32,32} anchor:{0.5,0.5} rotation:0.00 as an NSUserDefaults/CFPreferences value for key heroObjectKey
这是因为我无法保存自己的自定义对象,还是不喜欢对象中的某些属性值?
注意:有一个非常类似的问题部分地解决了我的问题,但由于Swift3与他们使用的任何东西之间的差异,那里接受的答案对我不起作用.所以我会在这里提供答案.
答案是使用keyedArchiver将对象转换为NSData对象.这是用于存储和检索对象的Swift 3代码:
原文链接:https://www.f2er.com/swift/319508.htmlfunc saveGame() { UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: hero),forKey: HeroObjectKey) } func defaultExistsForGameData() -> Bool { var gameData = false if let heroObject = UserDefaults.standard.value(forKey: HeroObjectKey) as? NSData { hero = NSKeyedUnarchiver.unarchiveObject(with: heroObject as Data) as! Hero gameData = true } return gameData }