2012-02-08 75 views
0

我無法確定爲什麼無法找到db.sqlite。我將它添加到項目的資源目錄中。它在那裏。 這裏是我如何檢查現有的一些代碼。找不到數據庫文件

-(void)getDatabaseLocation 
{ 
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *docsDir = [dirPaths objectAtIndex:0]; 

    // Build the path to the database file 
    NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"db.sqlite"]]; 

    NSFileManager *filemgr = [NSFileManager defaultManager]; 
    if ([filemgr fileExistsAtPath: databasePath ] == NO) 
    { 
     NSLog(@"NO"); // It's say no when this method is called. 
    } 
    else 
    { NSLog(@"YES"); 
    } 
} 

//編輯 現在我檢查,在DOCSDIR的路徑不存在。

回答

2

當然它不在那裏。您必須首先將資源複製到文檔目錄,如下所示:

if (![filemgr fileExistsAtPath:databasePath]) 
{ 
    [filemgr copyItemAtPath:[NSBundle.mainBundle pathForResource:@"db" ofType:@"sqlite"] toPath:databasePath error:nil]; 
} 

編輯:如果你只需要對數據庫做(沒有編輯)上查找,那麼你可以簡單地這樣做:

databasePath = [NSBundle.mainBundle pathForResource:@"db" ofType:@"sqlite"]; 
+0

他只需要將其複製到docdir,如果他想修改它。僅查找它可以簡單地保留在資源目錄中。 – 2012-02-08 15:05:31

+0

我只需要數據庫的SELECT語句 – Profo 2012-02-08 15:06:34

+0

@Profo我編輯我的答案,如果你不需要一個可寫的數據庫。 – 2012-02-08 15:07:59