Saving app data with the iPhone SDK and Cocoa is easy with NSUserDefaults

By | May 20, 2009

A quick look at NSUserDefaults suggests saving app data with Cocoa and the iPhone SDK is easy. I haven’t gotten much of a chance to use it so there might be some gotchas.

To store nonsensitive data using NSUserDefaults is as easy as a couple of lines of code:

[objc]
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:usernameTextField.text forKey:@"username"];
[defaults synchronize];
[/objc]

The last line is particularly important as it actually saves the data to disk.

Retrieving data is equally as easy:

[objc]
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog([defaults objectForKey:@"username"]);
[/objc]

NOTE: Using NSUserDefaults is a really bad idea for sensitive data like passwords. A significantly safer solution would be to use the iPhone’s keychain. Apple has an example found in GenericKeychain.

The API can be difficult to understand and cumbersome to use. Luckily, there is a solution for that from Buzz Anderson and it can be found on github.

Leave a Reply

Your email address will not be published. Required fields are marked *