2012-01-17 55 views
1

我使用sqlite和fmdb包裝。我對負載DB代碼是這樣的:ios fmdb從文件加載db

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docsPath = [paths objectAtIndex:0]; 
NSString *path = [docsPath stringByAppendingPathComponent:@"biscuit.sqlite"]; 
FMDatabase *db = [FMDatabase databaseWithPath:path]; 

我添加biscuit.sqlite到我的項目,但是這個代碼創建新的文件,而不是打開現有的。我怎樣才能加載這個文件?

回答

2

如果你只是想從你的數據庫中讀取數據,嘗試使用下面的代碼:如果你需要讀/寫訪問

NSString *path = [[NSBundle mainBundle] pathForResource:@"biscuit" ofType:@"sqlite"]; 

,你有你的數據庫,首先複製到可寫的用戶文件夾。

NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSError *error; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDir = [paths objectAtIndex:0]; 
NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"biscuit.sqlite"]; 
BOOL success = [fileManager fileExistsAtPath:dbPath]; 
if (!success) { 

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

    if (!success) { 
     NSLog(@"Failed to create writable DB. Error '%@'.", [error localizedDescription]); 
    } else { 
     NSLog(@"DB copied."); 
    } 
}else { 
    NSLog(@"DB exists, no need to copy."); 
} 
+0

這將讓你的應用程序被拒絕,使用不同的路徑:http://stackoverflow.com/questions/13896757/apps-must-follow-the-ios-data-storage-guidelines-or-they-將被拒絕在應用程序 – luqmaan 2014-03-06 03:26:01

+0

我可以在文檔文件夾中放置「.sqlite」後綴嗎? @luqmaan – Itachi 2016-06-17 09:16:00