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!

Advertisements




Fix: SharedPreferences not saved after app restart

21 09 2012

It is quite common error that SharedPreference setting is being reset or cleared to default, after Android application is restarted. There are two things you have to remember.

Commit changes made by prefs editor (the obvious one)

prefsEditor.commit();

Clear prefs editor before using it (the tricky one)

prefsEditor.clear();

The clear() method clears your preferences made by editor. Clear() is also always called in commit() method (so after the change in editor was made).

Summary

So to solve this problem You need to write code like this (compare it with snippets in previous post):

public static void setPushEnabledFlag(Context context, boolean newValue) {
	SharedPreferences prefs = context.getSharedPreferences(Constants.SP_MY_APPLICATION_SETTINGS, 0);
	Editor prefsEditor = prefs.edit();
	prefsEditor.clear();
	prefsEditor.putBoolean(
			context.getString(R.string.settingsActivity_ReceivePushNotifications_key),
			newValue);
	prefsEditor.commit();
}

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!








%d bloggers like this: