Persist data on iOS device

walden systems, objective c, geolocation, ios, CLLocationManager, desiredAccuracy, distanceFilter, startUpdatingLocation, stopUpdatingLocation, delegate, iphone, picture, screen, swipe, iphone, thread, nsthread, uitableviewcell, uitableview, initwithFName, infocellcontroller, nsdate, nsdateformatter nsstring, uuid, time, sleep, uiimage, UIGraphicsBeginImageContext, drawinrect, cgrectmake, nsuserdefaults, standarduserdefaults, setobjectforkey, objectforkey
Objective-C defines a small but powerful set of extensions to the ANSI C programming language that enables sophisticated object-oriented programming. Objective-C is the native language for Cocoa programming—it’s the language that the frameworks are written in, and the language that most applications are written in. You can also use some other languages—such as Python and Ruby—to develop programs using the Cocoa frameworks. It’s useful, though, to have at least a basic understanding of Objective-C because Apple’s documentation and code samples are typically written in terms of this language.

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"];