2010-11-01 24 views
0

我的應用程序使用數據庫,並在開始時我想檢查數據庫是否已被複制到文檔目錄。如果不是,它應該被複制到那裏。iphone SDK:如何將數據庫複製到iphone?

有沒有人知道下面的代碼可能有什麼問題。它的工作對我罰款,直到今天早上...出於某種原因,在iphone的documentsDirectory創建的數據庫完全是空的....

- (void)viewDidLoad { 
[super viewDidLoad]; 
self.databaseName = @"iWorkoutDatabase"; 
NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDir = [documentsPath objectAtIndex:0]; 
self.databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain]; 
} 

- (void)checkAndCreateDatabase{ 
BOOL databaseIsSaved; 

NSFileManager *fileManager = [NSFileManager defaultManager]; 
databaseIsSaved = [fileManager fileExistsAtPath:databasePath]; 
if (databaseIsSaved == YES) { 
    return; 
} 
else { 

    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName]; 
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil]; 

} 
[fileManager release]; 

} 

我快要瘋了試圖弄清楚這一點使這將是偉大的,如果有人可以幫助我... 編輯:我添加了相關的代碼從viewDidLoad方法,我看着從iPhone模擬器的文件路徑和文件實際上創建那裏,但它是一個空的.. ..

回答

1

代碼應該工作,我想。不過,也有一些東西留下來提高也可能會解決你的問題:

  • 不釋放一個共享實例 - 你的情況不要鬆開fileManager
  • 使用pathForResource:ofType:得到您的文件的完整路徑直接,而不是創建自己的路徑

  • 數據庫路徑從哪裏來?設置是否正確?

  • 您是否檢查過您的應用程序附帶的數據庫文件,可能是壞了?
  • 你嘗試做一個乾淨的構建?
+0

你能告訴我如何做一個乾淨的構建:)? – Chris 2010-11-01 14:00:45

+0

不幸的是沒有這些工作..... – Chris 2010-11-01 16:18:48

+0

我解決了它非常感謝你! – Chris 2010-11-01 17:07:46