How to use NSCoding to Save Custom Object to Array with NSUserDefaults in Swift?
<p>I have a custom object (which is a dictionary of strings) that is created when the user taps a button.</p>

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

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

<p>I have declared <code>createdObjectsArray</code> as:</p>

<pre><code>var createdObjectsArray = NSUserDefaults.standardUserDefaults().objectForKey("createdObjectsArray") as? [CustomObject] ?? [CustomObject]()
</code></pre>

<p>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.</p>

<p>See below my declaration of <code>CustomObject</code>:</p>

<pre><code>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");
    }
}
</code></pre>

<p>I'm not actually getting any error messages outputted into the console when items are added to this array, instead, the <code>createdObjectsArray</code> 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). </p>