Saving a Dictionary in NSUserDefaults

class AddElementVC: UIViewController {

    // textfields and some other functions are defined here 

    @IBAction func addElement(sender: UIBarButtonItem) {

        let newElement = Element(/* properties are defined here */)
        var theDict = NSUserDefaults.standardUserDefaults().dictionaryForKey(tableViewData) as [String: [Element]]

        if var theArray = theDict[newElement.someProperty] {
            theArray += newElement
            theDict[newElement.someProperty] = elementArray
        } else{
            theDict[newElement.someProperty] = [newElement]
        }

        NSUserDefaults.standardUserDefaults().setObject(theDict, forKey: tableViewData)

    }
}

EXPLANATION OF CODE ABOVE:

My tableView-app gets its data from a dictionary of the type [String: [Element]] (Element is a user class), which is loaded from userDefaults. In the second viewController, you can fill in some text fields and finally click UIBarButtonItem. A new instance of the Element class is created from the textFields data and added to theDict in the key of one of the newElement properties. All this works great when I checked it using console outputs, but I can’t finally save the edited dictionary in userDefaults. There are no syntax errors, but when I use the application and try to add another element to the dictionary through the second viewController, the following error is displayed:

error messages:

NSForwarding: warning: object 0xdcb002c '_TtC12myApp7Element' SignatureForSelector: -

.

import Foundation

class Element: NSCoding {

enum State: String {
    case state1 = "state1"
    case state2 = "state2"
}

let state: State
// some more properties

init(state: String /* something more */ ){
    self.state = State.fromRaw(state)!
    // something more
}

init(coder aDecoder: NSCoder!) {
    self.state = aDecoder.decodeObjectForKey("state") // displays error: 'AnyObject' is not convertible to 'Element.State'
    // something more
}

func encodeWithCoder(aCoder: NSCoder!) {
    aCoder.encodeObject(self.state, forKey: "state") // displays error: Extra Argument 'forKey' in call
    // something more
}

}
+3
1

NSUserDefaults:

value : NSData, NSString, NSNumber, NSDate, NSArray NSDictionary. NSArray NSDictionary, . . " ?" .

Element .

, , Element NSCoding, NSKeyedArchiver, NSData:

// Storing the dictionary
var data = NSKeyedArchiver.archivedDataWithRootObject(theDict)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: tableViewData)

// Retrieving the dictionary
var outData = NSUserDefaults.standardUserDefaults().dataForKey(tableViewData)
var dict = NSKeyedUnarchiver.unarchiveObjectWithData(outData)

:

init(coder aDecoder: NSCoder!) {
    self.state = State.fromRaw(aDecoder.decodeObjectForKey("state") as String)
}

func encodeWithCoder(aCoder: NSCoder!) {
    aCoder.encodeObject(self.state.toRaw(), forKey: "state")
}

Enum, , .

+13

All Articles