class AddElementVC: UIViewController {
@IBAction func addElement(sender: UIBarButtonItem) {
let newElement = Element()
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
init(state: String ){
self.state = State.fromRaw(state)!
}
init(coder aDecoder: NSCoder!) {
self.state = aDecoder.decodeObjectForKey("state")
}
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(self.state, forKey: "state")
}
}