开发者

Storing data in SQLite database after closing session in iPhone app

I am building an iPhone app using Objective-C that stores data in a SQLite database. The problem I'm having is that when my application is running, I'm able to make certain changes to the data in the table. Specifically, I need to allow the user to click on a button and select certain restaurants from the list as being a "favourite" (true), or "unfavourite" (false).

When my simulator is running, the code works fine. However, when I close my session and restart the app, the changes that I made in my previous session are not saved. Here is the relevant block of code:

- (void) addFavourite:(NSString *)rName{


sqlite3 *database;

NSString *updateString = nil;
NSString *trueStatement = @"true";

NavButtonAppDelegate *delegate = [[UIApplication sharedApplication] delegate];

if (sqli开发者_JAVA百科te3_open([delegate.databasePath UTF8String], &database) == SQLITE_OK) {

    updateString = @"UPDATE gtarestaurant set isFavourite = ? WHERE name = ?";
    const char *sqlStatement = [updateString UTF8String];
    sqlite3_stmt *compiledStatement;

    if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {

        sqlite3_bind_text(compiledStatement, 1, [trueStatement UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 2, [rName UTF8String], -1, SQLITE_TRANSIENT);


        while (sqlite3_step(compiledStatement) == SQLITE_ROW) {


        }

        sqlite3_finalize(compiledStatement);


    }

    sqlite3_close(database);

}

}

Can anyone see where I am going wrong? It appears that my problem is committing my changes to the database, after the user makes them


Use:

if(SQLITE_DONE != sqlite3_step(compiledStatement))
    NSAssert1(0, @"Update error: '%s'", sqlite3_errmsg(database));

instead of:

    while (sqlite3_step(compiledStatement) == SQLITE_ROW) {


    }

There are many ways the update could be failing such as the table not being there, or a field name being misspelled. This should give you an error telling you why the update did not process. If you don't want the app to stop use NSLog instead of NSAssert.

Also: you should have an else statement coupled with your if (sqlite3_open()) to notify you or the user that the database wasn't opened properly.


Thanks very much for all of your solutions. I found out that the problem was that the changes I thought I had made to my SQLite table had not gone through, and therefore my code was never writing any updates to the table. I had to actually go and make the changes via a database explorer to the location of the database being used by the iPhone simulator as part of the app in order for the code to correctly process the updates. Thanks very much Deepmist, and theChrisKent for taking the time to post your solutions. I really appreciate it. Take care.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜