// // Caches.m // Geopher Lite // // Created by Branden Russell on 8/30/08. // Copyright 2008 Equis International. All rights reserved. // #import "Caches.h" #import "Cache.h" #define DATABASE_FILE_NAME @"cachesdb.sql" @implementation Caches @synthesize caches; // Open the database connection and retrieve minimal information for all objects. - (void)initializeDatabase { NSMutableArray *array = [[NSMutableArray alloc] init]; self.caches = array; [array release]; // The database is stored in the application bundle. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:DATABASE_FILE_NAME]; // Open the database. The database was prepared outside the application. if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) { // Get the primary key for all caches. const char *sql = "SELECT pk FROM cache"; sqlite3_stmt *statement; // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library. // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator. if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) { // We "step" through the results - once for each row. while (sqlite3_step(statement) == SQLITE_ROW) { // The second parameter indicates the column index into the result set. int primaryKey = sqlite3_column_int(statement, 0); // We avoid the alloc-init-autorelease pattern here because we are in a tight loop and // autorelease is slightly more expensive than release. This design choice has nothing to do with // actual memory management - at the end of this block of code, all the cache objects allocated // here will be in memory regardless of whether we use autorelease or release, because they are // retained by the caches array. Cache *cache = [[Cache alloc] initWithPrimaryKey:primaryKey database:database]; [caches addObject:cache]; [cache release]; } } // "Finalize" the statement - releases the resources associated with the statement. sqlite3_finalize(statement); } else { // Even though the open failed, call close to properly clean up resources. sqlite3_close(database); NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database)); // Additional error handling, as appropriate... } } // Removes a cache from the array of caches, and also deletes it from the database. There is no undo. - (void)removeCache:(Cache *)cache; { // Delete from the database first. The cache knows how to do this (see Cache.m) [cache deleteFromDatabase]; [caches removeObject:cache]; } // Creates a new cache object with default data. - (void)addCache:(Cache *)cache; { // Create a new record in the database and get its automatically generated primary key. [cache insertIntoDatabase:database]; [caches addObject:cache]; } @end