2012-03-27 24 views
0

我遇到以下代碼加載SQLite數據庫的問題。Sqlite數據庫加載失敗 - 問題與SQLite準備語句 - iPhone - xCode 4.3.1

- (NSArray *)getDatabase { 

NSLog(@"Get Database Called"); 

    NSMutableArray *retval = [[[NSMutableArray alloc] init] autorelease]; 
    NSString *query = @"SELECT Description, UniqueID, HexCoords, NoHexCoords, NoAnnots, AnnotText, DescriptionFormatting, HexCoordsPortrait FROM MainTable"; 
    sqlite3_stmt *statement; 
    if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) 
     == SQLITE_OK) { 
     while (sqlite3_step(statement) == SQLITE_ROW) { 

      char *nameChars = (char *) sqlite3_column_text(statement, 0); 
      char *desChars = (char *) sqlite3_column_text(statement, 1); 
      int uniqueID = sqlite3_column_int(statement, 2); 

從使用斷點,我可以看到的問題是與if語句和代碼永遠不會越過這個if語句。任何人都可以發現什麼可能是錯的?代碼在幾個月前工作,我最近升級到xCode 4.3,所以這可能是問題嗎?

提前致謝。

+0

唯一的原因,我可以看到這樣的表現是,如果_database沒有正確設置。也許打電話來打開數據庫?另外,最後一個參數應該是'NULL',而不是'nil',因爲參數不是指向對象的指針。目前都編譯爲0,所以不應該導致問題,但我不知道他們會保持相同的任何保證。 – 2012-03-27 10:36:34

回答

1

是的,我同意約阿希姆。有時候DB有沒有真正連接的問題。我做的是幾件事情。首先我在應用程序代理中添加以下代碼。

- (void) copyDatabaseIfNeeded { 

    //Using NSFileManager we can perform many file system operations. 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSString *dbPath = [self getDBPath]; 
    BOOL success = [fileManager fileExistsAtPath:dbPath]; 

    if(success) { 

     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyDB.sqlite"]; 
     success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error]; 

     if (!success) 
      NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    } 
} 

在ApplicationDidFinishLaunching中調用此函數。

現在刪除當前在你的包中的數據庫。 (請確保你有它的備份)。並且(如果可能,從Iphone Simulator文件夾中刪除所有項目)Coz有時會附加上一個數據庫。 清理您的項目,在ur包中添加數據庫。編譯..

讓我知道,如果它的工作

的獲取通道功能

- (NSString *) getDBPath { 
     //Search for standard documents using NSSearchPathForDirectoriesInDomains 
     //First Param = Searching the documents directory 
     //Second Param = Searching the Users directory and not the System 
     //Expand any tildes and identify home directories. 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
     NSString *documentsDir = [paths objectAtIndex:0]; 
     return [documentsDir stringByAppendingPathComponent:@"MYDB.sqlite"]; 
} 
+0

謝謝 - 但什麼是「getDBPath」的方法? – GuybrushThreepwood 2012-03-27 11:00:16

+0

對不起忘了提到 – WaaleedKhan 2012-03-27 11:18:45

+0

還有一件事我想補充..在函數u張貼在你的問題你設置返回類型爲(NSArray *)它不是最好的做法..你應該使用NSMutableArray – WaaleedKhan 2012-03-27 11:29:40