2011-01-20 77 views
10

我剛開始使用iPhone開發。在其中一個示例中,我必須在tabbar控制器的表視圖中顯示一些存儲在sqlite數據庫中的數據,我必須將sqlite文件從應用程序包移動到documents文件夾。iPhone:如何將文件從資源複製到文檔?

我使用的應用模板 - 的iOS>應用>對於iPhone基於窗口的應用程序(存儲用於核心數據)

在通過的XCode(基SDK設置爲最新的iOS = 4.2)生成的模板,下面的代碼在那裏......

- (NSURL *)applicationDocumentsDirectory { 
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
} 

在試圖讓文檔文件夾的路徑,我用上面這樣給出的方法...

NSString *documentDirectory = [self applicationDocumentsDirectory]; 

這給給出警告NG - warning: incompatible Objective-C types initializing 'struct NSURL *', expected 'struct NSString *'

所以我改變了代碼如下...

// Added the message absoluteString over here 
NSString *documentDirectory = [[self applicationDocumentsDirectory] absoluteString]; 

NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:@"mydb.sqlite"]; 
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydb.sqlite"]; 
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
if (!success) { 
    NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
} 

呯!它給出了錯誤 - 'Failed to create writable database file with message 'The operation couldn’t be completed. No such file or directory'.'

我該如何找到文檔目錄的路徑,因爲由XCode模板生成的方法applicationDocumentsDirectory不適用於我。

另外,有人可以拋開上面給出的applicationDocumentsDirectory方法的目的。

謝謝

+0

我得到的錯誤,因爲我沒有在writableDBPath添加的文件名。這個例子幫助我修復它。謝謝! +1 – voghDev 2014-11-26 11:52:16

回答

5

我剛剛在幾天前遇到了這個問題。不要強制路徑下的東西,包含NSURL路徑。如何使用它們不需要很短的時間。

至於方法,它只是要求系統提交一個URL到應用程序的標準化文檔目錄。使用這個和大多數關於您放置新文件的位置都是正確的。

+0

更多詳情請點擊這裏? :( – 2014-11-07 09:57:32

20

繼承人一個簡單的方法來做到這一點:

NSFileManager *fmngr = [[NSFileManager alloc] init]; 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"mydb.sqlite" ofType:nil]; 
    NSError *error; 
    if(![fmngr copyItemAtPath:filePath toPath:[NSString stringWithFormat:@"%@/Documents/mydb.sqlite", NSHomeDirectory()] error:&error]) { 
     // handle the error 
     NSLog(@"Error creating the database: %@", [error description]); 

    } 
    [fmngr release]; 
+2

Rich你是對的,但有點過時從目前的文檔:「這將始終返回文件管理器的相同實例。返回的對象不是線程安全的。 在Mac OS X v 10.5和後來你應該考慮使用[[NSFileManager alloc] init]而不是singleton方法defaultManager。使用[[NSFileManager alloc] init]來代替,所得到的NSFileManager實例是線程安全的。「 – 2011-01-22 22:18:20

相關問題