簡體   English   中英

iPhone:如何將文件從資源復制到文檔?

[英]iPhone: How to copy a file from resources to documents?

我剛開始使用iPhone開發。 在我必須在tabbar控制器的表視圖中顯示存儲在sqlite db中的一些數據的示例之一中,我不得不將sqlite文件從應用程序包移動到documents文件夾。

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

在由XCode生成的模板中(基本sdk設置為最新iOS = 4.2),以下代碼在那里......

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

在嘗試獲取文檔文件夾的路徑時,我使用上面給出的方法,就像這樣......

NSString *documentDirectory = [self applicationDocumentsDirectory];

這給出了一個警告 - 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'.' 'Failed to create writable database file with message 'The operation couldn't be completed. No such file or directory'.'

我應該如何找到文檔目錄的路徑,因為XCode模板生成的方法applicationDocumentsDirectory對我不起作用。

此外,有人可以說明上面給出的applicationDocumentsDirectory方法的目的。

謝謝

這是一個簡單的方法:

    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];

我幾天前就碰到了這個。 不要強行沿路徑路徑,包含NSURL路徑。 獲得如何使用它們不會花費很短的時間。

至於方法,它只是要求系統將URL提供給應用程序的標准化文檔目錄。 使用此以及關於放置新文件的位置的大部分內容都是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM