6/22/2009

[iPhone] Saving Simple Data

My hacked (for apps) iPhone & an iPod Touch at...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 *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}
Above: 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"

-(void)applicationWillTerminate:(NSNotification *)notification
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: [NSNumber numberWithFloat:sliderValue]];
[array addObject: [NSNumber numberWithFloat:segmentValue]];
[array writeToFile:[self dataFilePath] atomically: YES];
[array release];
}
Above: 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.
Reblog this post [with Zemanta]

6 comments:

  1. It's an interesting tutorial. Thanks. :)

    ReplyDelete
  2. Did anyone tried this on a device?
    For me it does not work.
    Cocoa error 513...

    ReplyDelete
  3. hm, well it worked for me on device and on simulator. Probably your code didn't fetch the filepath correctly.

    ReplyDelete
  4. This is just what I needed! Can you do this with html? Cause you used plist. I am making high scores basically trying to add a UILabel's text to an html file which the label is the score. If you can help me my AIM is: littlesirkaz

    Thanks for the tutorial.

    ReplyDelete
  5. I never thought about html, but you could do it with xml which would be fine for both the iPhone and your web server

    ReplyDelete
  6. Can you Help ME? I Givw you my email.
    magonicolas@gmail.com

    ReplyDelete