Persist data on iOS device
NSUserDefaults is the Objective-C class that allows you to store and retrieve user preferences for your application. Stored as NSData associated with a string key, the defaults are persisted to a local database on your user’s OS. For performance reasons, these are placed in memory, and occassionally synchronized back to the database. To get started with NSUserDefaults, you should first register the default values for each setting the user can control. You can then read or write to the NSUserDefaults class using the objectForKey: and the setObject:forKey: methods. You can read more about the NSUserDefaults class under the developer documentation: NSUserDefaults Class Reference page, and the Preferences and Settings Programming Guide.
OK, let’s start setting the default user preferences. To do this, we will create an appDefaults NSMutableDictionary instance, and assign objects that we want to store. Then, we are going to store an Int. Finally, we are going to get access to the shared NSUserDefaults instance object calling the class method standardUserDefaults on the NSUserDefaults class.
1 -(void)setDefaultUserPreferences 2 { 3 //create dictionary to hold defaults 4 NSMutableDictionary *appDefaults = [NSMutableDictionary dictionary]; 5 6 //add integer 7 int anyInt = 5; 8 [appDefaults setInteger:someInteger forKey:@"integer_field"]; 9 10 //register the application defaults 11 [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; 12 }
To retrieve the data use the following:
int newInt = [[NSUserDefaults standardUserDefaults]integerForKey:@"integer_field"];