In this blog, you will find how to manage user default records by storing & retrieving into NSUserDefaults.

By using NSUserDefaults class we can store default settings, preferences or any such default values in string or dictionary or array format. It can be achieved with just a few lines of code & it loads data faster. Its usually used for storing small data where no such complex operations are required to perform.

The main advantage of using NSUserDefaults for storing a small number of values is it loads data faster than other storage options. More importantly, it doesn’t block the main thread. So it’s not slowing down UI operations & make sure app runs smoothly. That’s why NSUserDefaults class is threaded safe.

Here are simple steps for storing, retrieving & removing data from NSUserDefaults.


Saving data to NSUserDefaults :

Objective C :

[[NSUserDefaults standardUserDefaults] setObject:strUsername forKey:@”username”];

[[NSUserDefaults standardUserDefaults] synchronize];

Swift :

UserDefaults.standard.set(strUsername, forKey: “username”)

Read more: Top 10 must have WooCommerce Plugins for WordPress site

Retrieving data to NSUserDefaults :

Objective C :

strUsername = [[NSUserDefaults standardUserDefaults] stringForKey:@”username”]

Swift :

let strUsername : String = UserDefaults.standard.value(forKey: “username”) as! String

Removing NSUserDefaults value :

Objective C :

[[NSUserDefaults standardUserDefaults]  removeobjectForKey:@”username”];

Swift :

UserDefaults.standard.removeObject(forKey: “username”)