Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store [String] in NSUserDefaults

I want to save a Swift Style String Array into NSUserDefaults, but acutally the "if" statement in the code says that returnValue is always nil.

Later in the code (iOS 8) I want to use "food += ["spaghetti"] to add new entries.

var food : [String] {
    get {
        var returnValue : [String]? = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String]
        if returnValue == nil      //Check for first run of app
        {
            returnValue = ["muesli", "banana"]; //Default value
        }
        return returnValue!
    }
    set (newValue) {
        NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}
like image 232
Thomas Avatar asked Aug 21 '14 07:08

Thomas


People also ask

How to store string in swift?

To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:) method of the UserDefaults class. We also need to pass a key as the second argument to the set(_:forKey:) method because we are creating a key-value pair.

What types can you store natively in NSUserDefaults?

Storing Default Objects The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs. These methods are described in Setting Default Values.

Is NSUserDefaults thread safe?

The NSUserDefaults class is thread-safe.

How do you save NSUserDefaults in Objective C?

static func setObject(value:AnyObject ,key:String) { let pref = NSUserDefaults. standardUserDefaults() pref. setObject(value, forKey: key) pref. synchronize() } static func getObject(key:String) -> AnyObject { let pref = NSUserDefaults.

How to read and store data in nsuserdefaults?

There are several convenience methods for storing data in NSUserDefaults they include: Reading is done in a very similar fashion. You need to get a reference to the NSUserDefaults object, and then ask it for the value you want. In the case of reading out the String we wrote in and printing it to the console, we would use the code:

How to save custom objects into the nsuserdefaults?

[ [NSUserDefaults standardUserDefaults] setObject:@"Netherlands" forKey:@"HomeCountry"]; To save custom objects into the `NSUserDefaults` you need to make your CustomClass confirm to protocol of `NSCoding`.

What is nsuserdefaults in Android?

An interface to the user’s defaults database, where you store key-value pairs persistently across launches of your app. The NSUserDefaults class provides a programmatic interface for interacting with the defaults system.

What is nsuserdefaults class in Java?

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user’s preferences.


3 Answers

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) // prints: ["muesli", "banana"] (at first launch)

        food = ["cake"]
        print(food) // prints: ["cake"]

        food += ["spaghetti"]
        print(food) // prints: ["cake", "spaghetti"]

        food = []
        print(food) // prints: []

        NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "food")
        print(food) // prints: ["muesli", "banana"]
    }

}

However, with the previous code, if you set food = [], you will have a problem as food won't return ["muesli", "banana"]. In order to avoid this, you may prefer the following code:

import UIKit

class ViewController: UIViewController {

    var food: [String] {
        get {
            if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
                return returnValue == [] ? ["muesli", "banana"] : returnValue
            } else {
                return ["muesli", "banana"] //Default value
            }
        }
        set {
            NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(food) // prints: ["muesli", "banana"] (at first launch)

        food = ["cake"]
        print(food) // prints: ["cake"]

        food += ["spaghetti"]
        print(food) // prints: ["cake", "spaghetti"]

        food = []
        print(food) // prints: ["muesli", "banana"]

        NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "food")
        print(food) // prints: ["muesli", "banana"]
    }

}
like image 199
Imanou Petit Avatar answered Oct 08 '22 09:10

Imanou Petit


As stated in the documentation:

For NSArray and NSDictionary objects, their contents must be property list objects.

This means you need to convert your String objects to NSString when saving, something like this should work:

var food : [String] {
    get {
        var returnValue : [String]? = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String]
        if returnValue == nil      //Check for first run of app
        {
            returnValue = ["muesli", "banana"]; //Default value
        }
        return returnValue!
    }
    set (newValue) {
        //  Each item in newValue is now a NSString
        let val = newValue as [NSString]
        NSUserDefaults.standardUserDefaults().setObject(val, forKey: "food")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}
like image 13
pNre Avatar answered Oct 08 '22 07:10

pNre


In Swift 3.0

Store

UserDefaults.standard.set(newValue, forKey: "yourkey")
UserDefaults.standard.synchronize()

Retrieve

var returnValue: [NSString]? = UserDefaults.standard.object(forKey: "yourkey") as? [NSString]

Remove

UserDefaults.standard.removeObject(forKey: "yourkey")

Reference: NSUserdefault objectTypes

like image 9
Sina Avatar answered Oct 08 '22 09:10

Sina