简体   繁体   中英

How to use NSCoding to Save Custom Object to Array with NSUserDefaults in Swift?

I have a custom object (which is a dictionary of strings) that is created when the user taps a button.

When this object is created, I am using the following code to add and then store it in an array:

    createdObjectsArray.append(createdObject) // Append the object to the array
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(createdObjectsArray), forKey: "createdObjectsArray")
            NSUserDefaults.standardUserDefaults().synchronize()

I have declared createdObjectsArray as:

var createdObjectsArray = NSUserDefaults.standardUserDefaults().objectForKey("createdObjectsArray") as? [CustomObject] ?? [CustomObject]()

However, my code to save the array does not appear to be working as the number of elements contained within the array is 0 when the application is closed completely on iOS.

See below my declaration of CustomObject :

class CustomObject : NSObject, NSCoding {

    var objectName: String?
    var objectColour: String?
    var objectWeight: String?

    init(json: NSDictionary) { // Dictionary object
        self.objectName = json["objectName"] as? String
        self.objectColour = json["objectColour"] as? String
        self.objectWeight = json["objectWeight"] as? String
    }

    required init?(coder aDecoder: NSCoder) {

        self.objectName = aDecoder.decodeObjectForKey("objectName") as? String;
        self.objectColour = aDecoder.decodeObjectForKey("objectColour") as? String;
        self.objectWeight = aDecoder.decodeObjectForKey("objectWeight") as? String;
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.objectName, forKey: "objectName");
        aCoder.encodeObject(self.objectColour, forKey: "objectColour");
        aCoder.encodeObject(self.objectWeight, forKey: "objectWeight");
    }
}

I'm not actually getting any error messages outputted into the console when items are added to this array, instead, the createdObjectsArray is simply blank. I have suspicions that the issue is either the original declaration of my object or the way in which I am saving the items to the array (by simply appending it).

You cannot store array of custom object into NSUserDefaults .

I think the best option for you is use NSKeyedArchiver to convert your array into NSData , and store this data in NSUserDefaults

Some code for you:

let array: [CustomObject] = [...]
let data = NSKeyedArchiver.archivedDataWithRootObject(array)
createdObjectsArray.setObject(data, forKey: "createdObjectsArray")

To read data:

if let savedData = createdObjectsArray.objectForKey("createdObjectsArray") as? NSData {
    if let array = NSKeyedUnarchiver.unarchiveObjectWithData(savedData) as? [CustomObject] {
        // do something…
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM