9

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
zeeple
  • 5,509
  • 12
  • 43
  • 71
  • 2
    Possible duplicate of [Saving custom SWIFT class with NSCoding to UserDefaults](http://stackoverflow.com/questions/26469457/saving-custom-swift-class-with-nscoding-to-userdefaults) – Alexander Mar 14 '17 at 04:26
  • Thanks @Alexander as it happens that question got me close but there are syntax problems with the answers over there, so I am posting my answer here. – zeeple Mar 14 '17 at 04:59
  • Possible duplicate of [Attempt to insert non-property list object when trying to save a custom object in Swift 3](http://stackoverflow.com/questions/41355427/attempt-to-insert-non-property-list-object-when-trying-to-save-a-custom-object-i) – Nirav D Mar 14 '17 at 05:19

1 Answers1

16

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
}
zeeple
  • 5,509
  • 12
  • 43
  • 71