Matt Galloway

My home on the 'net.

SQLite Persistent Objects

I have been playing with SQLite recently and toying with the idea of creating some kind of framework upon which I could build persistent data objects, much like the Zend way of doing things in Zend Framework for PHP. That was, until I came across SQLite Persistent Objects

SQLite Persistent Objects is written by Jeff Lamarche and it is a framework which specifies a single class which you can extend to give SQLite persistent abilities to that object. The basic functionality goes like this:

1
2
3
4
5
6
7
8
9
10
11
#import "SQLitePersistentObject.h"

@interface Person : SQLitePersistentObject  {
  NSString *name;
  NSString *email;
}

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;

@end
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "Person.h"

@implementation Person

@synthesize name, email;

- (void)dealloc {
        [name release];
        [email release];
        [super dealloc];
}

@end

Now, within your application you can use something along these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "SQLiteInstanceManager.h"
#include "Person.h"

...

// Set the database path
[[SQLiteInstanceManager sharedManager] setDatabaseFilepath:@"database.sqlite"];

// Create a new person, set it up and save it
Person *newPerson = [[Person alloc] init];
newPerson.name = @"Joe Bloggs";
newPerson.email = @"joe.bloggs@example.com";
[newPerson save];
[newPerson release];

Then, SQLite Persistent Objects will create the table if necessary and add the new person to the table. It really is that simple. You can even have multiple objects derived from SQLitePersistenObject which contain references to each other and when you call save on them, they will notice the links and sort things out so that the database tables contain sufficient references to each other to persist that link. Another great feature is the ability of the code to remember what has been loaded previously and keep it in memory so that it doesn’t do unnecessary loading.

If you’re thinking of using SQLite in your iPhone / iPod Touch / Cocoa app, then be sure to check out SQLite Persistent Objects!

Comments