Trying to encode custom objects to NSData in Swift


#1

I’m trying to save an array of a custom object (DreamSign) to user preferences. One of the properties of DreamSign is also a custom enum. I found out I have to encode these objects to NSData in order to save them. Is there a section of any of the big nerd ranch books that can help with this? I have the swift book, and I was last in the properties section.

I’ve tried a few ways but I can’t figure it out with the info that’s online. This is the struct I’m trying to encode.

struct DreamSign {

var name = "Default Dream Sign"
var dreaminess = Dreaminess.neutral

enum Dreaminess: Int {
    case neutral    = 9
    case somewhatLikely = 30 
    case likely     = 50 
    case veryLikely = 90 
    case definetly   = 99 
    }
}

#2

Take a look at this post: [Encoding Structs] (Structs? on classes only in NSCoding), and see if you can benefit from it.


#3

Thanks. I also found information on encoding in the iOS programming book. But yea I realized it can’t be done easily with structs. The post you gave is a bit above my level- I’ve not come across an “extension” yet. I might just convert my struct to a class if I can’t get it to work.