Data Persistance on the iPhone

If you’re writing apps for the iPhone, sooner or later you will want to be able to persist data between sessions. You might want to store hi-scores, preferences, favorites, log metrics or achieve some other task. The iPhone supports three main interfaces for persisting data, ultimately they all write out to disk. In time you will probably find you use all three methods, each one suits different tasks.

Property Lists

Property lists, or plists, offer a way to write a dictionary of data (key – value pairs) out to a file. The native format is XML file, but you don’t need to load the file and parse it, you can simply read the file and de-serialize the information back into objects. To write out, you just create your dictionary object and serialize it to a file. Plists offer a lightweight method to store data and work well when you have a clearly defined set of objects to persist, perfect for hi-scores, favorites and preferences. Read the data in your application delegate in applicationDidFinishLaunching, and write it back out in applicationWillTerminate.

Reading and writing to Plists is pretty trivial. Once your ‘favorites’ data is stored in a dictionary:-

- (void)writeToFavorites: (NSDictionary *) myFavorites
{
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *filePath = [path stringByAppendingPathComponent:@"favorites.plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
                                      initWithContentsOfFile:filePath];
    [plistDict setValue:myFavorites forKey:@"Favorites"];
    [plistDict writeToFile:filePath atomically: YES];
}

…and to read it back in again:-

- (NSDictionary *) readFavorites
{
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *filePath = [path stringByAppendingPathComponent:@"favorites.plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
                                      initWithContentsOfFile:filePath];
    NSDictionary *myFavorites = [plistDict objectForKey:@"Favorites"];
    return myFavorites;
}

Plists support various data types including strings, numbers, arrays and dictionaries, so they can be used to store complex data structures and best of all, there’s no parsing to do!

SQLite

For more complex data interactions, nothing beats a good old fashioned database.  SQLite has been available on iPhone since its launch and historically was used in Apple’s core applications.  SQLite is available across platforms and is the workhorse for tasks inside many applications, for example Firefox uses  SQLite for tracking downloads, bookmarks, history and other tasks.

SQLite offers a lightweight SQL interface to your data.  Your application must create tables and write data into them using SQL commands.  As it’s name suggests, SQLite is ‘lite’ – although it offers RDBMS functionality, it has some quirky features when compared to traditional RDBMSs such as Oracle, Microsoft SQL Server, MySQL or PostgreSQL.  For example, most data formats boil down to a string representation, this leads to the dynamic typing capabilities of Perl or PHP!  Binary data can be stored in SQLite databases which means that whole objects can be stored out in much the same way that Plists can store data objects.

Working with SQLite on iPhone requires tools to support being able to view the state of your data as you develop your application.  Because of the app’s sandbox environment, you will need to store your database in the Documents folder inside your app directory.  There are a number of viewers for SQLite databases, I use the SQLite Manager plugin for Firefox which is perfectly adequate. When compiling for iPhone simulator you can drill down into the application directoryand view your database in situ,  To view a database on your iPhone, first you must pull the SQLite file onto your Mac using Xcode’s Organiser.  Download the database to your local disk and then open in the manager.  Be aware that each time you compile your app for Simulator, the app id changes, moving the database location with every run.

In order to use SQLite in your own projects, you must add the framework into your project in Xcode.  Right click on the Frameworks folder in your Xcode project and choose ‘Add existing framework…’.  SQLite is located at:-

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOSx.x.sdk/usr/lib/libsqlite3.0.dylib

Make sure that you select ‘libsqlite3.0.dylib’ as this always points to the latest build of the version 3 framework.

The main SQLite website offers full documentation, learn more there about what SQL features are and are not supported.

Core Data:

This Cocoa framework was made available to iPhone OS 3 and is Apple’s preferred way to persist data.  Under the bonnet, Core Data actually uses either SQLite or Plists to store your data – it makes the choice.  Although this is Apple’s preferred method for persisting data, it may not be yours!

As with SQLite you must add the Core Data framework to your project – this is located with the other Cocoa frameworks.  Use Xcode’s Data Modeller to create your data structure, this is much like creating a SQL database with a GUI tool.  Once you’ve done that, Core Data methods give you a powerful interface to your data.

One good reason to favour SQLite over Core Data is that SQLite is more portable, and if you are looking to migrate your app between iPhone and Android, then you’ll be able to share code more easily.  Core Data does give you some pretty compelling features should you need them – undo capabilities in your app, spell checking and it automatically looks after persisting your data to disk.

- (void)readPlist
{
    NSString *filePath = @"/System/Library/CoreServices/SystemVersion.plist";
        NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

        NSString *value;
        value = [plistDict objectForKey:@"ProductVersion"];

        /* You could now call the string "value" from somewhere to return the value of the string in the .plist specified, for the specified key. */
}
Share this:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • MySpace
  • StumbleUpon
  • Twitter
  • Yahoo! Buzz

This post was written by:

- who has written 11 posts on Mindsizzlers.


Contact the author

Leave a Reply

Advert

For more information about our services…

Contact Us

Wordle of the Day

Image from software at http://wordle.net
Data by Web Trends Now

Categories