iOS tutorial: Using NSUserDefaults

NSUserDefaults are meant to persist small amounts of data in Key-Value convention on iPhone (same as SharedPreferences on Android).

The idea is to save some object or primitive under the key. Objects that can be stored are for example of type NSString or NSArray. These will be accessible from anywhere in your application, and will persist after the application is closed. You should not use it for storing data larger than 500kb or custom Objects.

You can store there for example user’s settings or preferences, like user’s name or email. Technically it is stored in XML or binary file on the file system, however it is conveniently wrapped in SDK enabling you to call it in one line. That is how you use it:

1. Store value in NSUserDefaults

[[NSUserDefaults standardUserDefaults] setObject:@"John" forKey:@"USER_NAME_KEY"];

2. Read stored value from NSUserDefaults

NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:@"USER_NAME_KEY"];

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

Give Your feedback: