mike vorisis
mike vorisis

Reputation: 2832

Save Dictionary into NSUserDefaults Swift

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

Upvotes: 2

Views: 1625

Answers (3)

mike vorisis
mike vorisis

Reputation: 2832

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.

Upvotes: 0

gurmandeep
gurmandeep

Reputation: 1247

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

Upvotes: 0

Gabriel J. S. Oliveira
Gabriel J. S. Oliveira

Reputation: 104

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]

Upvotes: 2

Related Questions