这是代码...有人看错了吗?此外,为什么在调试设备(iPhone 3GS)时,“ errmsg”的第二个NSLog导致调试器崩溃

    // 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 *fileManager = [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);
        }

最佳答案

之所以崩溃,是因为errmsg不是一个Objective-C对象,您需要使用%@替换。 errmsgchar *,表示您应该使用%s

至于为什么崩溃...

sqlite3_open定义为:

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


您的db被声明为sqlite3*。换句话说,您传递的是错误的内容。您应该这样做:

sqlite3_open(cDatabasePath, &db)


尽管您对理解SQLite C API的渴望很大,但我仍然认为您应该使用FMDB。它确实可以减轻这类错误,并让您专注于代码的实际问题。

关于objective-c - 尝试打开(创建)SQLite d/b时出错(“EXC_BAD_ACCESS”),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5796115/

10-12 01:50