Cannot set non-property-list object in UserDefaults

zeeple picture zeeple · Mar 14, 2017 · Viewed 14.6k times · Source

I have a simple function in which I save an object to user defaults for the purpose of loading it back in 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 the error:

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

Is this because I cannot save my own custom objects, or does it not like some property value within the object?

Note: there is a very similar question which partially resolved my issue, but the accepted answer there did not work for me due to differences between Swift3 and whatever they were using. So I will provide the answer here.

Answer

zeeple picture zeeple · Mar 14, 2017

The answer was to use keyedArchiver to convert the object to an NSData object. Here is the Swift 3 code for storing, and retrieving the 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
}