How do I save an array of classes into NSUserDefaults?

Hi, I have a custom class:


class ImageListItem {
        var image_name:String = ""
        var image_url:NSURL = NSURL()
        var security_bookmark_data:NSData = NSData()

    init(imageName: String, imageURL: NSURL, secBookmarkData: NSData)
    {
        image_name = imageName
        image_url = imageURL
        security_bookmark_data = secBookmarkData
    }

    init (coder a_decoder: NSCoder!) {
        self.image_name = a_decoder.decodeObjectForKey("image_name") as! String
        self.image_url = a_decoder.decodeObjectForKey("image_url") as! NSURL
        self.security_bookmark_data = a_decoder.decodeObjectForKey("sec_data") as! NSData
    }

    func encodeWithCoder(a_coder: NSCoder!) {
        a_coder.encodeObject(image_name, forKey:"image_name")
        a_coder.encodeObject(image_url, forKey:"image_url")
        a_coder.encodeObject(security_bookmark_data, forKey: "sec_data")
    }
}


and an array of these classes:


var array_image_list:[ImageListItem] = []



I'd like to store the array in NSUserDefaults when my app quits and after looking around the web I found answers which pointed to adding the init (coder...) and encodeWithCoder(...) methods. One answer I found (here) in particular indicated using:


let prefs = NSUserDefaults()
if self.array_image_list.count > 0 {
            let keyed_archiver: NSData = NSKeyedArchiver.archivedDataWithRootObject(self.array_image_list)
            prefs.setObject(keyed_archiver, forKey: prefs_image_list)

}


to save to the prefs but I get the error


*** NSForwarding: warning: object 0x600000274d80 of class 'myApp.ImageListItem' does not implement methodSignatureForSelector: -- trouble ahead


Is there a way of saving Swift arrays to NSUserDefaults?

Accepted Reply

Because archiving/unarchiving is a Cocoa technology, it only works on Obj-C objects. So, you actually need:


class ImageListItem: NSObject, NSCoding
{ … }


Keep in mind that there are some subtle differences in what you can do with Obj-C objects vs. Swift objects, so this might have an impact on your code elsewhere. But chances are you won't notice any difference.

Replies

Because archiving/unarchiving is a Cocoa technology, it only works on Obj-C objects. So, you actually need:


class ImageListItem: NSObject, NSCoding
{ … }


Keep in mind that there are some subtle differences in what you can do with Obj-C objects vs. Swift objects, so this might have an impact on your code elsewhere. But chances are you won't notice any difference.