App force关闭清除SQLite条目

时间:2015-01-29 17:24:37

标签: objective-c sqlite ios7

我使用以下方法创建了SQLite数据库。当用户首次登录时,我向该数据库插入少量记录。在后续登录时,我使用此信息进行进一步处理。只要用户不使用approach described here强行关闭应用,这种方法就可以正常运行。

如果用户强制关闭并再次登录应用,则他/她输入的所有信息都将丢失。现在我的问题是,我怎样才能确保"强制关闭"不会消灭我的数据?任何帮助赞赏。

onViewLoad,根据需要创建表格:

//Database code start.
    NSArray *dirPaths;
    NSString *docsDir;
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];
    _databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingString:@"users.db"]];

    sqlite3* db = NULL;
    int rc=0;

    rc = sqlite3_open_v2([_databasePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    if (SQLITE_OK != rc)
    {
        sqlite3_close(db);
        NSLog(@"Failed to open db connection");
    }
    else
    {
        char * query ="CREATE TABLE IF NOT EXISTS USERS(username TEXT, userid INTEGER NOT NULL)";
        char * errMsg;
        rc = sqlite3_exec(db, query,NULL,NULL,&errMsg);

        if(SQLITE_OK != rc)
        {
            NSLog(@"Failed to create table rc:%d, msg=%s",rc,errMsg);
        }

        sqlite3_close(db);
    }
    //END of table creation.

on"登录按钮单击"

//Start SQLite DB operation.
                        sqlite3* db = NULL;
                        int rc=0;
                        rc = sqlite3_open_v2([_databasePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE , NULL);
                        if (SQLITE_OK != rc)
                        {
                            sqlite3_close(db);
                            NSLog(@"Failed to open db connection");
                        }
                        else
                        {
                            NSString *insertSQL = [NSString stringWithFormat:
                                                   @"INSERT INTO USERS(username, userid) values (\"%@\",\"%@\")",
                                                   uName,uID];
                            char * errMsg;
                            rc = sqlite3_exec(db, [insertSQL UTF8String] ,NULL,NULL,&errMsg);
                            if(SQLITE_OK != rc)
                            {
                                NSLog(@"Failed to insert record  rc:%d, msg=%s",rc,errMsg);
                            }
                            sqlite3_close(db);
                        }

                        //End of sqlite DB operation.

只要用户不强行关闭应用,数据就不会消失。

修改

花了很多时间后,我发现文件夹路径是正确的,但我得到了#34;无法打开数据库文件"电话问题。

1 个答案:

答案 0 :(得分:0)

经过长时间的痛苦调试后,我确定了这个问题:

 _databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingString:@"users.db"]];

应该是:

 _databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"users.db"]];

令人惊讶的是,第一种方法在模拟器中运行良好,并且像this这样的互联网上的大多数示例都使用第一种方法。