目标C:将文件或文件夹从url复制到新文件夹

时间:2014-02-27 21:30:05

标签: objective-c macos

我正在为os x上复制或剪切的所有数据构建一个归档程序。如何将存储在fileUrl中的文件或目录复制到新目录?我现在得到的URL的一个例子是file:///.file/id=6562758.59150379

NSArray *fileUrl = [[NSArray alloc] initWithObjects:[NSURL class], nil];
NSDictionary *options = [NSDictionary dictionary];

//pasteboard = [NSPasteboard generalPasteboard];
NSArray *object1 = [pasteboard readObjectsForClasses:fileUrl options:options];

if (object1 != nil){
    NSLog(@"%@", object1);
}

2014-02-27 12:31:22.451 Copy&Cut Archive[17720:303] (
    "file:///.file/id=6562758.59150379"
)

2 个答案:

答案 0 :(得分:3)

从概念上讲,使用粘贴板是有道理的,但最好放弃粘贴板并使用NSFileManager的方法来移动和复制文件。

你有几个选择......

移动和复制项目

– copyItemAtURL:toURL:error:

– copyItemAtPath:toPath:error:

– moveItemAtURL:toURL:error:

– moveItemAtPath:toPath:error:

答案 1 :(得分:0)

更新: 这就是我将文件或目录复制到新文件夹的方式。

NSFileManager *fm = [NSFileManager defaultManager];
NSDictionary *options = [NSDictionary dictionary];
NSArray *fileURL = [[NSArray alloc] initWithObjects:[NSURL class], nil];
NSArray *object1 = [pasteboard readObjectsForClasses:fileURL options:options];

if ([object1 count] > 0){
    NSURL *frURL_source = [object3 objectAtIndex:0];

    //convert file reference URL to path-based URL
    NSURL *fpURL_source = [frURL_source filePathURL];

    //dirName is NSString path to the archive directory
    NSString *filePath = [NSString stringWithFormat:@"%@%@", dirName, toWrite];

    NSURL *fpURL_dest = [NSURL fileURLWithPath:filePath];

    [fm copyItemAtURL:fpURL_source toURL:fpURL_dest error:nil];
}