开发者

SQLite iphone data lost when rebooting or closing the app

I have a question... I have an application using sqlite to save some data.Everything works perfectly, meaning I can add, delete, view data. The data are persistent when the application goes into background. Now, when I remove the application from memory or reboot the iPhone, the database is corrupted and all the data are messed up !

I have a class call dbAccess where all the database actions are define(add, delete, retreive rows). At the end I have a finalize action, that finalize all the statement used and then close the database.

+ (void)finalizeStatements{

NSLog(@"Finalizing the Delete Statements");
if(deleteStmt) {
    NSLog(@"Delete Statement exist... finalization");
    sqlite3_finalize(deleteStmt);
    deleteStmt = nil;
}
NSLog(@"Finalizing the Add Statements");
if(addStmt) {
    NSLog(@"Add Statement exist... finalization");
    sqlite3_finalize(addStmt);
    addStmt = nil;
}
NSLog(@"Finalizing the Store Statements");
if(storeStmt) {
    NSLog(@"Store Statement exist... finalization");
    sqlite3_finalize(storeStmt);
 开发者_运维百科   storeStmt = nil;
}
NSLog(@"Finalizing the Agent Statements");
if(agentStmt) {
    NSLog(@"Agent Statement exist... finalization");
    sqlite3_finalize(agentStmt);
    agentStmt = nil;
}

NSLog(@"Closing the Database");
if(database) {
    NSLog(@"The database exist... closing it");
    sqlite3_close(database);
}

}

This method is called by the application delegate when applicationDidEnterBackground and applicationWillTerminate. An openDatabase method is call when applicationDidBecomeActive.

Any ideas why the database is corrupted ?

Thanks.


First off, check out fmdb or some other proven wrappers. You can also browse the code.

Not sure if there's enough info to know why it's corrupt. But, you should get return codes from ALL sqlite3_xxx calls and log at a minimum to understand what's going on or you may just be blasting past an issue.

Also, make sure to call sqlite_errmsg which will offer more clues if the return code is not success.

In my wrapper, I do this in close. It's expected that statements are finalized bu handled if not. I have a statement cache which on clear finalizes each statement. :

- (void)close
{
    if (_sqlite3)
    {
        NSLog(@"closing");
        [self clearStatementCache];

        int rc = sqlite3_close(_sqlite3);
        NSLog(@"close rc=%d", rc);

        if (rc == SQLITE_BUSY) 
        { 
            NSLog(@"SQLITE_BUSY: not all statements cleanly finalized");

            sqlite3_stmt *stmt; 
            while ((stmt = sqlite3_next_stmt(_sqlite3, 0x00)) != 0) 
            {
                NSLog(@"finalizing stmt");
                sqlite3_finalize(stmt); 
            }

            rc = sqlite3_close(_sqlite3);
        }

        if (rc != SQLITE_OK)
        {
            NSLog(@"close not OK.  rc=%d", rc);
        }

        _sqlite3 = NULL;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜