Intro to NSUserDefaults in Swift

Last week I’ve had a brief blog discussing the pros and cons between NSUserDefaults and Core data. Today I want to continue to talk about NSUserDefaults, and how to actually implement it. Great! Let’s get right to it!

As I’ve mentioned in my last blog, NSUserDefaults is best used to store small size data such as user’s default settings. For any large amount of data, I would suggest you use Core Data instead. Any data type that conforms to NSData, NSString, NSNumber, NSDictionary, or NSDate can be stored using NSUserDefaults.

Step one: Create an instance

Like most cases in Swift, we want to create an instance of UserDefaults first.

let userDefault = UserDefaults.standard

Step two: Set the value

userDefault.set("Hello", forKey: "greeting")

We can then use that instance to set any value from the types that I’ve mentioned. You can put anything on forKey , it is just a key like you would use in a Dictionary .

That’s it! With 2 lines of codes you can save any data that conforms to NSUserDefaults. Simple right? Now let’s learn how to read the data.

Reading NSUserDefaults

let userDefault = UserDefaults.standard
if let theGreeting = defaults.stringForKey("greeting") {

In order to read from NSUserDefaults, we need to first create an instance. Our next step is to find if our value does exist. Here I used an if-let statement to check if a such a value exist. If it does return nil, I can simply set my new key and value in my else statement. An important thing I want to note is that we need to create an new instance for every function that we have placed NSUserDefaults. We cannot create a property that we can use throughout the class.

And thats how you implement NSUserDefaults. It is pretty simple and straightforward. I hope you guys find this blog helpful. Thanks for tuning in!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.