Iphone Developer Technological

Using NSUserDefaults

This is handy when saving credentials to a device so the user doesn’t have to re-login every time he launches the app. NOTE: This is not useful for saving large amounts of data or data that will change frequently. Use iCloud or persistent state stores such as databases or xml or plist files for that!

Once you have the data you wish to save somewhere in your app, call the following:

// call the store object
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// set an object for it
[prefs setObject:imageView.image forKey:@”keyToLookupImage”];
// call sync to save it
[prefs synchronize];

then later in the beginning or launch of an app you can get that data like so:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = nil;
//If myString = nil, then do all this, otherwise do nothing…
UIImage *retrievedImage = [prefs stringForKey:@”keyToLookupImage”];
imageView.image = retrievedImage;

You have just saved your user a good deal of grief and he’ll thank you for it!

Translate »