Unable to set non-property-list object to UserDefaults

I have a simple function in which I save the default object for the user for the purpose of loading it later, it looks like this:

func saveGame() { // hero is an instance of the class Hero, subclassed from SKSpriteNode UserDefaults.standard.set(hero, forKey: HeroObjectKey) } 

I get an error message:

2017-03-13 21:15: 33.124271 Lock [5405: 5208658] [User default settings] Attempt to set the name of a non-property-list object: texture 'hero': ['hero1.ico' (32 x 32)]: scale {0, 0}: {1.00, 1.00} size: {32, 32} anchor: {0.5, 0.5} rotation: 0.00 as the value of NSUserDefaults / CFPreferences for the key heroObjectKey

Is this because I cannot save my own custom objects or do not like any property value inside the object?

Note: there is a very similar question that partially solved my problem, but the accepted answer there did not work for me because of the differences between Swift3 and what they used. Therefore, I will provide an answer here.

+7
swift3
source share
1 answer

The answer was to use keyedArchiver to convert the object to an NSData object. Here is the Swift 3 code for storing and retrieving an object:

 func 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 } 
+12
source share

All Articles