I have an app with 4 or 5 SQL Tables open.
When the user taps the home button and applicationDidEnterBackground is called I save all dirty records into the tables:
[self.shoppingListArray makeObjectsPerformSelector:@selector(saveAllData)];
...
- (void)saveAllData {
if(isDirty) {
if(updateStmt == nil) {
const char *sql = "UPDATE ShoppingList SET Section = ?, Question = ?, Checked = ?, Modified = ? WHERE ID = ?";
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
NSLog(@"DIRTY Item Was Updated: %@", Question);
sqlite3_bind_text(updateStmt, 1, [Section UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, [Question UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 3, isChecked ? [@"YES" UTF8String]:[@"NO" UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 4, isModified ? [@"YES" UTF8String]:[@"NO" UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_int(updateStmt, 5, ID);
if(SQLITE_DONE != sqlite3_step(updateStmt))
NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(开发者_JAVA百科database));
sqlite3_reset(updateStmt);
isDirty = NO;
}
//Reclaim all memory here.
[Section release];
Section = nil;
[Question release];
Question = nil;
isDetailViewHydrated = NO;
}
Then I finalize statements and close database:
[ShoppingListInformation finalizeStatements];
...
+ (void) finalizeStatements {
if(database) sqlite3_close(database);
if(deleteStmt) sqlite3_finalize(deleteStmt);
if(updateStmt) sqlite3_finalize(updateStmt);
if(addStmt) sqlite3_finalize(addStmt);
}
So, the question is what do I do when applicationWillEnterForeground is called?
Do I reopen databases and repopulate my arrays and reload table views?
What is the best practice of how to approach this and not lose user data, restore state, etc?
Any help appreciated!
I would suggest not closing the db or finalizing statements unless the app is closing (applicationWillTerminate:). Then you will come back into the app in the same state you left it, no action required. I'm not positive this is the most efficient way to do it but it has worked for me.
精彩评论