如何在applicationDidEnterBackground上保存SQL数据/关闭DB并在applicationWillEnterForeground上继续

时间:2011-05-23 22:06:12

标签: iphone sql

我有一个打开4或5个SQL表的应用程序。

当用户点击主页按钮并调用applicationDidEnterBackground时,我将所有脏记录保存到表中:

[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(database));

        sqlite3_reset(updateStmt);

        isDirty = NO;
    }
    //Reclaim all memory here.
    [Section release];
    Section = nil;
    [Question release];
    Question = nil;
    isDetailViewHydrated = NO;
}

然后我完成语句并关闭数据库:

[ShoppingListInformation finalizeStatements];

...

+ (void) finalizeStatements {
    if(database) sqlite3_close(database);
    if(deleteStmt) sqlite3_finalize(deleteStmt);
    if(updateStmt) sqlite3_finalize(updateStmt);
    if(addStmt) sqlite3_finalize(addStmt);
}

所以,问题是当调用applicationWillEnterForeground时我该怎么做?

我是否重新打开数据库并重新填充数组并重新加载表视图?

如何处理此问题并且不丢失用户数据,恢复状态等的最佳做法是什么?

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

除非应用程序正在关闭(applicationWillTerminate :),否则我建议不要关闭db或finalizing语句。然后,您将以离开它的相同状态返回应用程序,无需任何操作。我不是肯定的,这是最有效的方法,但它对我有用。