How do I use UserDefaults with SwiftUI?

The approach from caram is in general ok but there are so many problems with the code that SmushyTaco did not get it work. Below you will find an “Out of the Box” working solution. 1. UserDefaults propertyWrapper import Foundation import Combine @propertyWrapper struct UserDefault<T> { let key: String let defaultValue: T init(_ key: String, … Read more

Store [String] in NSUserDefaults

The following code should help you resolve your problem: import UIKit class ViewController: UIViewController { var food: [String] { get { if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(“food”) as? [String] { return returnValue } else { return [“muesli”, “banana”] //Default value } } set { NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: “food”) NSUserDefaults.standardUserDefaults().synchronize() } } override func viewDidLoad() { super.viewDidLoad() print(food) … Read more

How to set initial values for NSUserDefault Keys?

You should use the registerDefaults method of NSUserDefaults. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults. NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:@”defaultPrefs” ofType:@”plist”]; NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile]; [[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences]; You have to execute this code on every launch of your … Read more

What are the limitations of NSUserDefaults?

Sqlite3 is more useful for keeping large database and to access to the database elements. You can sort the items of Sqlite3 database, you can search very fast for item in Sqlite3 dtabase. Sqlite3 database has many privileges that NSUserDefaults didn’t have ! NSUserDefaults vs Sqlite3 NSUserDefaults is for user preferences, usually basic objects like … Read more

NSUserDefaults losing its keys & values when phone is rebooted but not unlocked

I was having a very similar issue. Background the application. Use other memory heavy applications till my application gets jettisoned from memory. (You can observe this event if you have your device plugged and xcode running the build. Xcode will tell you “application was terminated due to memory pressure). From here if your application is … Read more

Swift – How to set initial value for NSUserDefaults

Swift 3 syntax example Register a boolean default value: UserDefaults.standard.register(defaults: [“SoundActive” : true]) And to get the value: UserDefaults.standard.bool(forKey: “SoundActive”) Sidenote: Although the above code will return true, note that the value isn’t actually written to disk until you set it: UserDefaults.standard.set(true, forKey: “SoundActive”)