Monday, June 7, 2010

4 ways to save data in iphone

Saving data is very important in many applications. May it be games or other applications, data persistence is essential. There are mainly 4 ways to save data in iphone. They are as follows:

1. User Defaults:
This is probably the easiest and simplest way to save data in iphone. You can save the plist objects ie NSData, NSString, NSArray, NSNumber, NSDate and NSDictionary using user defaults. Other data types like floats, doubles, integers, booleans can also be saved using user defaults. Lets see some examples.

Saving:
[[NSUserDefaults standardUserDefaults] setInteger:5 forKey:@"number"];
[[NSUserDefaults standardUserDefaults] setObject:@"hello" forKey:@"string"];


Retrieving:
NSInteger i = [[NSUserDefaults standardUserDefaults] integerForKey:@"number"];
NSString *s = [[NSUserDefaults standardUserDefaults] objectForKey:@"string"];


2. Files:
Data can also be saved in files using file manager. The following code shows an example of how an array is saved in a file named file.plist in the document directory and retreived later.

//save data
-(void)saveData{
      NSString *path = [(NSString *) [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.plist"];
      NSArray *dataArray = [NSArray arrayWithObjects:@"item1",@"item2",nil];
      [dataArray writeToFile:path atomically:YES];
}

//load data
- (void) loadData {
      NSString *path = [(NSString *) [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.plist"];
      if ([[NSFileManager defaultManager] fileExistsAtPath: path]) {
            NSArray *dataArray= [[NSArray alloc] initWithContentsOfFile: path];       }
      else {
            NSLog(@"File not found");
      }
}


3. SQLite Database:
If you need a full-blown database functionality, iphone provides you with the ability to use SQLite databases. You can have databases and write normal SQL queries. But ever since the introduction of core data in iphone OS 3, core data is much preferred than using raw SQLite. Internally core data also uses SQLite but it abstracts all the ugly details of underlying SQLite. If you are planning to use SQLite, I would suggest you to use core data instead. But if you are curious and want to learn how to use SQLite, there is a very nice 4 part tutorial at icodeblog.

4. Core Data:
As I said earlier, core data is an abstraction layer that sits on top of SQLite database. Majority of people prefer core data to using raw SQLite. But the learning curve is a more steep. You will find quite a lot of new concepts and terminologies in core data which can be quite intimidating at the beggining. Also it is a quite a big topic that entire books have been written on it. If you are really willing to master core data, then Core Data for iPhone by Tim Isted might be the book for you. Apple's tutorials for core data is also a good place to start learning core data.

Sunday, June 6, 2010

Saving persistent data on iphone while application exits

In many instances you would want to save application data when user exits your application. Since exiting an application programmatically is forbidden, the only way to exit any application in iphone is to press the home button. So how would you be able to save the data when user exits your application?

When the home button is pressed the UIApplication's delegate method applicationWillTerminate is called. So you can put the code to save your persistent data inside this method in your appDelegate class.

- (void)applicationWillTerminate:(UIApplication *)application{
//code to save your data
//If you don't know how data is saved, view this post on saving data in iphone
}


But there is still one problem. Since the above method will be in you appDelegate class, it might be troublesome to save data in other view controller classes. To solve this problem you can subscribe to notification named UIApplicationWillTerminateNotification.

-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appTermination:) name: @"UIApplicationWillTerminateNotification" object: nil];
}

-(void)appTermination:(id)sender{
//code to save your data
//If you don't know how data is saved, view this post on saving data in iphone
}


What this does is that it subscribes for the UIApplicationWillTerminateNotification notification in viewDidLoad method and sets appTermination method to be called when this notification is received