iOS tutorial: Using NSUserDefaults

26 01 2013

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:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: