Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Monday, 16 March 2009

Saving data to files

In some circumstances you want to save data to disk, in some cases you will use a database for that. But if you need , for example, to save the highscores of a game then a database will be a bit overkill.

In that case you can use core data, so lets look at a small example of how this works.
(Consider you already have an application in which you want to include a mechanism to save data).

Step 1 : add a data model

In XCode , you open the file assistant (via File>New File) and select 'data model'



Once you defined the data model , you'll get something like this :


I already added an Entity called HighScores , you add the entity via the menuitem (Design>Data Model>Add Entity).
I a same fashion you can add attributes to the entity (Desgin>Data Model>Add Attribute).
In my case I just defined 3 attributes : name,rank and score.

So this is all their is to define a datamodel (of course this is a very simple datamodel).
Now we need some coding to save information to the datamodel (and to file).

Step 2 : datastore identification

First we need to define in which file we will store the information :

NSError *error ; // this is for error reporting ; see later

NSURL *url = [NSURL fileURLWithPath:@"/Users/Herman/file.xml"];

Step 3 : define the datamodel we will use (= the datamodel in the project)

NSArray *bundles = [NSArray arrayWithObject:[NSBundle mainBundle]];

NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:bundles];

Step 4 : associate the datamodel with the datastore (= the file) via a coordinator

NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
[coordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options: nil error:&error];

Step 5 : Get the context

context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator: coordinator];

Step 6 : Save some data to the file

NSManagedObject *score = [NSEntityDescription insertNewObjectForEntityForName:@"HighScores" inManagedObjectContext:context];
[score setValue:@"bla bla" forKey:@"name"] ;
[score setValue:[NSNumber numberWithInt: 100] forKey:@"score"] ;
[score setValue:[NSNumber numberWithInt: 1] forKey:@"rank"] ;
[context save: &error ] ;

Et voila, we have a simple way of saving data to a file.
In a next message I'll discuss how to retrieve data and do some more complex queries on files.