[英]iPhone (iOS): copying files from main bundle to documents folder causes crash
[英]iPhone (iOS): copying files from main bundle to documents folder error
我試圖在首次啟動時將我的應用程序包中的一些文件復制到文檔目錄。 我有第一次啟動的檢查,但為了清楚起見,它們未包含在代碼段中。 問題是我正在復制到文檔目錄(已經存在),在文檔中,它說明:
在操作之前, dstPath不得存在。
對我來說直接復制到文檔根目錄的最佳方法是什么? 我想這樣做的原因是允許iTunes文件共享支持。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"];
NSLog(@"\nSource Path: %@\nDocuments Path: %@", sourcePath, documentsDirectory);
NSError *error = nil;
if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error]){
NSLog(@"Default file successfully copied over.");
} else {
NSLog(@"Error description-%@ \n", [error localizedDescription]);
NSLog(@"Error reason-%@", [error localizedFailureReason]);
}
...
return YES;
}
謝謝
目標路徑必須包含要復制的項目的名稱,而不僅僅是文檔文件夾。 嘗試:
if([[NSFileManager defaultManager] copyItemAtPath:sourcePath
toPath:[documentsDirectory stringByAppendingPathComponent:@"Populator"]
error:&error]){
...
編輯:抱歉誤解了你的問題。 不知道是否有更好的選擇,然后迭代文件夾內容並分別復制每個項目。 如果你的目標是iOS4,你可以使用NSArray的-enumerateObjectsUsingBlock:
函數:
NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];
[resContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSError* error;
if (![[NSFileManager defaultManager]
copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj]
toPath:[documentsDirectory stringByAppendingPathComponent:obj]
error:&error])
DLogFunction(@"%@", [error localizedDescription]);
}];
PS如果您不能使用塊,您可以使用快速枚舉:
NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];
for (NSString* obj in resContents){
NSError* error;
if (![[NSFileManager defaultManager]
copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj]
toPath:[documentsDirectory stringByAppendingPathComponent:obj]
error:&error])
DLogFunction(@"%@", [error localizedDescription]);
}
一張紙條:
不要在didFinishLaunchingWithOptions中發出冗長的操作:這是一個概念上的錯誤。 如果這個副本花費太多時間,看門狗會殺了你。 在輔助線程或NSOperation中啟動它...我個人使用定時器proc。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.