Nsuserdefaults in Swift - Implementing Type Safety

NSUserDefaults in Swift - implementing type safety

I don't mean to brag but ... oh who am I kidding, I totally do!

Preferences.set([NSData()], forKey: "MyKey1")
Preferences.get("MyKey1", type: type([NSData]))
Preferences.get("MyKey1") as [NSData]?

func crunch1(value: [NSData])
{
println("Om nom 1!")
}

crunch1(Preferences.get("MyKey1")!)

Preferences.set(NSArray(object: NSData()), forKey: "MyKey2")
Preferences.get("MyKey2", type: type(NSArray))
Preferences.get("MyKey2") as NSArray?

func crunch2(value: NSArray)
{
println("Om nom 2!")
}

crunch2(Preferences.get("MyKey2")!)

Preferences.set([[String:[Int]]](), forKey: "MyKey3")
Preferences.get("MyKey3", type: type([[String:[Int]]]))
Preferences.get("MyKey3") as [[String:[Int]]]?

func crunch3(value: [[String:[Int]]])
{
println("Om nom 3!")
}

crunch3(Preferences.get("MyKey3")!)

How to save/load Set type by NSUserDefaults?

Convert the Set to Array which can be saved in NSUserDefaults

let arrayA = Array(setA)
NSUserDefaults.standardUserDefaults().setObject(arrayA, forKey:"mySet")

and get the array and convert it back to Set

let arrayA = NSUserDefaults.standardUserDefaults().objectForKey("mySet") as! [Int]
let setA = Set(arrayA)

If you register the key/value pair as Apple recommends

let defaults = NSUserDefaults.standardUserDefaults()
let defaultValues = ["mySet" : [Int]()]
defaults.registerDefaults(defaultValues)

the value is never nil and can be safely unwrapped.

security of NSUserDefaults in Swift

If you need security you should use Key Chains. It encodes values and is best way to save some security information. One thing that you should know is that you should not store there a lot of data as this storage is related to whole device not just to your application, so if your application will be deleted, stored data still will be alive. For example using User Defaults stored data would immediately become deleted(same with using Core Data).

NSUserDefaults optionals in Swift

You are force unwrapping your optionals, and you should get them as strings before appending them to your array.

A cleaner way to set the defaults would be to coalesce the unwrapping of your optionals, Try the following approach:

func getFiltersSetts() -> [String] {
let userDefs = NSUserDefaults.standardUserDefaults()
var defsArray = [String]()
defsArray.append(userDefs.stringForKey("gender") ?? "Male")
defsArray.append(userDefs.stringForKey("age") ?? "21-30")
defsArray.append(userDefs.stringForKey("online") ?? "Online")
return defsArray
}

The code above uses the coalesce (??) operator. If your optional, say userDefs.stringfForKey("gender"), returns nil, the coalesce operator will use the default value "Male".

Then at a later time you can save your user defaults (or create them) if they haven't been set before.

Also, is worth noticing that you should be unwrapping your optionals using the if let notation. Instead of comparing if its != nil, as this will prevent you from force unwrapping them inside the code block.

I hope this helps!

What are the limitations of NSUserDefaults?

NSUserDefaults offers a trivial learning curve and thread safe implementation.

Otherwise I've found Core Data superior in every way. Especially with regards to configuring default values and migration routines.

Edit: As it turns out, NSUserDefaults "thread-safeness" seems to come from running operations on the main-thread. This caused severe frame-skipping in one of my applications; I ended up ripping out NSUserDefaults and replacing it with a thread-safe NSMutableDictionary which gets serialized to a file.

Making NSUserDefault of type Integer in Swift

Swift 3:

You could just use the set(Int, forKey: String) method Swift provides:

//Set
UserDefaults.standard.set(yourInt, forKey: "intKey")
//Get
UserDefaults.standard.integer(forKey: "intKey")

Swift 2:

You could just use the setIntegerForKey-method Swift provides:

let defaults = NSUserDefaults.standardUserDefaults()

//Set
defaults.setInteger(yourInt, forKey: "intKey")
//Get
defaults.integerForKey("intKey")


Related Topics



Leave a reply



Submit