Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save dictionary to UserDefaults

I'm trying to store a dictionary in UserDefaults and always get app crash when the code runs. Here is the sample code which crashes the app when it is executed. I tried to cast it as NSDictionary or make it NSDictionary initially - got the same result.

class CourseVC: UIViewController {

let test = [1:"me"]

override func viewDidLoad() {
    super.viewDidLoad()

    defaults.set(test, forKey: "dict1")

    }

}
like image 1000
Roman Avatar asked Apr 15 '18 15:04

Roman


People also ask

Can we save a dictionary in UserDefaults?

UserDefault can save integers, booleans, strings, arrays, dictionaries, dates and more, but you should be careful not to save too much data because it will slow the launch of your app.

How do you save in UserDefaults?

Updating the Prospects initializer so that it loads its data from UserDefaults where possible. Adding a save() method to the same class, writing the current data to UserDefaults . Calling save() when adding a prospect or toggling its isContacted property.

How do I save a dictionary in Swift?

We access the shared defaults object through the standard class property of the UserDefaults class. We then create a dictionary of type [String:String] and store the dictionary in the user's defaults database by invoking the set(_:forKey:) method of the UserDefaults database.

How do you save Uicolor in UserDefaults?

The easiest way would be using NSUserDefaults . In this case you are storing the string "Coding Explorer" and you can reference by the key "userNameKey" .


1 Answers

Dictionaries are Codable objects by default, you can use the following extensions to save them to UserDefaults

extension UserDefaults {
    func object<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
        guard let data = self.value(forKey: key) as? Data else { return nil }
        return try? decoder.decode(type.self, from: data)
    }

    func set<T: Codable>(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
        let data = try? encoder.encode(object)
        self.set(data, forKey: key)
    }
}

They can be used like this:

let test = [1:"me"]
UserDefaults.standard.set(object: test, forKey: "test")

let testFromDefaults = UserDefaults.standard.object([Int: String].self, with: "test")

This extension and many others are part of SwifterSwift, you might want to use it for your next iOS project :)

like image 88
Omar Albeik Avatar answered Sep 21 '22 15:09

Omar Albeik