Image by Steve Rhodes via Flickr
This tutorial will show you an easy way of saving simple bits of data so that they can be continue to be used next time the app is started on your iPhone.Imagine you wanted to save some user settings. In this example I have a UISlider and a UISegmentedControler which I want the user to be able to set, but the iPhone should remember the settings and display them in their last state whenever the iPhone App is restarted.
In the .h file add:
float sliderValue;
float segmentValue; // Use these values to adjust your UI Elements
// You will also need the following methods:
-(NSString *)dataFilePath;
-(void)applicationWillTerminate:(NSNotification *)notification;
In the .m file add:
-(void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
sliderValue = [[array objectAtIndex:0] floatValue];
segmentValue = [[array objectAtIndex:1] floatValue];
[array release];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];
[super viewDidLoad];
}
Above: This is where we load the date if there is any from the last save on the iPhone. First, we check to see if the data file does already exist. If it doesn't, then we don't bother about it. If it does however, we instantiate an array with the contents of the file and add the content to our variable as a float. Remember to save and load them in the same order so you don't mix things up. After having done that, we add some extra code to subscribe to the Notification so that it calls the saving process before quiting the app.
-(NSString *)dataFilePathAbove: What this method does is return the full path of the the data file (data.plist). It does that by finding the documents directory on the iPhone/iPod Touch device and appending (adding) "data.plist"
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}
-(void)applicationWillTerminate:(NSNotification *)notificationAbove: The method will be called when, as you might have guessed, the application will get terminated/closed. Here is where you should add all the data you want to keep for the next time the iPhone loads the Application.
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: [NSNumber numberWithFloat:sliderValue]];
[array addObject: [NSNumber numberWithFloat:segmentValue]];
[array writeToFile:[self dataFilePath] atomically: YES];
[array release];
}