Getting and setting user preferences on iPhone is pretty darn easy. I was looking for a way to automagically store a users email address between different application sessions, and found the linked tutorial immensely helpful (iphonedevelopertips.com).
I needed to store a string (NSString object actually) however, and the tutorial didn’t help me with that. The NSUserDefaults object has dedicated methods for storing and retrieving BOOL, float, and NSInteger values. It also has a setObject:forKey: method - which is what I ended up using. The setObject method handles data of types NSData, NSString, NSDate, NSArray or NSDictitionary - making it incredibly useful indeed.
My Preferences.h
1 2 3 4 5 6 7 | |
My Preferences.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
kPreferencesEmailAddress is a constant I’ve defined with the key value of the users email address. It just makes sure I don’t mistype anything.
Key (only) differences between my code and the code at iphonedevelopertips.com are the use of the objectForKey method to set the NSString value, and stringForKey to retrieve the object and cast it to a NSString object.
Hope that helps someone!