2

I have a Dictionary and i want to save it to NSUserDefaults(or something else so I can have access to my variables after i have terminated the app) , I found an example:

var saved = NSUserDefaults.standardUserDefaults()
let dict = ["Name": "Paul", "Country": "UK"]
saved.setObject(dict, forKey: "SavedDict")

But when i used it to mine Dictionary it didn't work. (maybe because my dictionary it's a little bit different)

My Dictionary is made like this:

 var userDictionary = [Int : Event]()

 struct Event {
        var sensorName: String
        var sensorType: String
        var sensorSub: String

    }

And i add elements like this:

userDictionary[value] = Event(sensorName: "first", sensorType: "Temp", sensorSub: "Third")

And here is what i tried to do so I can store it.

saved.setObject(userDictionary, forKey: "valueDictionary")

And I get this error:

Cannot convert value of type '[Int : SensorsView.Event]' to expected argument type 'AnyObject?'

To avoid this error I did this:

self.saved.setObject(self.userDictionary as? AnyObject, forKey: "valueDictionary")

But I can't retrieve what i saved

Unfortunately this question didn't help me after some comments i believe that the goal here is to convert my dictionary to Data (or something else) and after i retrieve it i convert it back to Dictionary

Community
  • 1
  • 1
mike vorisis
  • 2,786
  • 6
  • 40
  • 74
  • 1
    From the Doc: `The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.` Event is not one of them, that's why we have in Objective-C to use the encode/decode. – Larme Jul 10 '16 at 21:52
  • Thank you @Larme i will try to find some info about this convertion if you have something in mind to look please answer me. – mike vorisis Jul 10 '16 at 21:55
  • For a small object like this one, you could use a `initWithDictionary:` method, and a `toDictionary`. Something that convert an`Event` object into `["Name":mySensorName,"Type":mySensorType, "Sub":mySensorSub"]` or something similar. – Larme Jul 10 '16 at 21:59
  • Ok i will do my research with these thank you again!! – mike vorisis Jul 10 '16 at 22:00
  • I think http://stackoverflow.com/questions/25752433/swift-nsuserdefaults-not-saving-dictionary or http://stackoverflow.com/questions/25109813/saving-dictionary-into-nsuserdefaults may help – gurmandeep Sep 09 '16 at 03:28

3 Answers3

2

Try to convert the data to NSData and then retrieve like so:

/// Save
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(object), forKey: key)

/// Read
var data = NSUserDefaults.standardUserDefaults().objectForKey(key) as NSData
var object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [String: String]
0

What i think is from the link below you will be able to store the Dictionary into NSUserDefaults

Swift NSUserDefaults not saving Dictionary? or

Saving dictionary into NSUserDefaults may help

Community
  • 1
  • 1
gurmandeep
  • 1,227
  • 1
  • 14
  • 30
0

I managed to save my custom Dictionary using Realm! Instead of a struct I use a different class like this:

import RealmSwift


class Sensors : Object {


    dynamic var sensorName = ""
    dynamic var sensorType = ""
    dynamic var sensorSub = ""

}

and then I fill it like this:

    var useOfRealm = try! Realm() 
    var allSensors = useOfRealm.objects(Sensors.self)
    var saving = Sensors()
    func fillThis() {
    try! useOfRealm.write {

                saving.sensorName = "something"
                saving.sensorType = "something"
                saving.sensorSub = "something"

                useOfRealm.add(saving)
    }
}

Use the function with parameters so you can fill the 'Dictionary' Dynamically.

Use allSensors so you can retrieve everything that you want.

mike vorisis
  • 2,786
  • 6
  • 40
  • 74