开发者

Error (“EXC_BAD_ACCESS”) while trying to open(create) SQLite d/b

开发者 https://www.devze.com 2023-03-01 09:19 出处:网络
Here\'s the code... anybody see what\'s wrong?Also, why does the 2nd NSLog of \"errmsg\" cause the debugger to crash when debugging to the device (iPhone 3GS)

Here's the code... anybody see what's wrong? Also, why does the 2nd NSLog of "errmsg" cause the debugger to crash when debugging to the device (iPhone 3GS)

    // Get the path to the database file
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];
NSString *databasePath = [documentPath stringByAppendingPathComponent:@"ppcipher.s3db"];
const char *cDatabasePath = [databasePath cStringUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"databasePath: %@", databasePath);

    NSString *sqlCommand = @"CREATE TABLE CardData (card_id TEXT PRIMARY KEY NOT NULL, card_name TEXT NOT NULL, "
        @"card_type TEXT, cide_val TEXT, create_date TEXT DEFAULT CURRENT_DATE, user_notes TEXT, gps_loc TEXT)"; 
    const char cSQLCommand = [sqlCommand cStringUsingEncoding:NSUTF8StringEncoding];
    char * errmsg = NULL;   

    NSFileManager *fileM开发者_开发知识库anager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:databasePath error:NULL];  //  <------------  delete d/b  TESTING ONLY! 

    BOOL fileExists = [fileManager fileExistsAtPath:databasePath];
    if(!fileExists)  {
        if(sqlite3_open(cDatabasePath, db) == SQLITE_OK) { // doesn't exist, so create it...
            sqlite3_exec(db, &cSQLCommand, NULL, NULL, &errmsg);  //  now create the table...
            NSLog(@"error: %@", errmsg);
        }


It's crashing because errmsg is not an Objective-C object, which you're requiring by your use of the %@ substitution. errmsg is a char *, which means you should be using %s.

As for why it's crashing....

sqlite3_open is defined as:

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

Your db is declared as sqlite3*. In other words, you're passing the wrong thing in. You should be doing:

sqlite3_open(cDatabasePath, &db)

While your desire to understand the SQLite C API is great, I still think you should use FMDB. It really mitigates these sorts of errors and lets you concentrate on the real problems with your code.

0

精彩评论

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