【发布时间】:2023-03-29 21:50:01
【问题描述】:
我需要从我的应用程序的资源文件夹中复制一些示例文件并将它们放在我的应用程序的文档文件夹中。我想出了附加的代码,它编译得很好,但它不起作用。我提到的所有目录都存在。我不太确定我做错了什么,有人可以指出我正确的方向吗?
NSFileManager*manager = [NSFileManager defaultManager];
NSString*dirToCopyTo = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString*path = [[NSBundle mainBundle] resourcePath];
NSString*dirToCopyFrom = [path stringByAppendingPathComponent:@"Samples"];
NSError*error;
NSArray*files = [manager contentsOfDirectoryAtPath:dirToCopyFrom error:nil];
for (NSString *file in files)
{
[manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:dirToCopyTo error:&error];
if (error)
{
NSLog(@"%@",[error localizedDescription]);
}
}
编辑:我只是按照应有的方式编辑了代码。然而现在还有另一个问题:
2010-05-15 13:31:31.787 写它 移动[4587:207] DAMutableDictionary.h 2010-05-15 13:31:31.795 写它 移动[4587:207] 文件管理器 错误:无法操作 完全的。文件存在
编辑:我已经通过告诉 NSFileManager 复制文件的目标名称来解决这个问题。
[manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:[dirToCopyTo stringByAppendingPathComponent:file] error:&error];
【问题讨论】:
-
不要抑制错误返回 (
contentsOfDirectoryAtPath:error:)。另外,对于copyItemAtPath:toPath:error:,在尝试使用错误对象之前测试方法是否失败;见rentzsch.tumblr.com/post/260201639/nserror-is-hard。
标签: iphone cocoa document nsfilemanager copying