正确地将对象移动到垃圾箱



在Cocoa上,有很多方法可以将文件/文件夹目录移动到垃圾桶:

  1. [[NSWorkspace sharedWorkspace]performFileOperation:NSWorkspaceRecycleOperation]
  2. [[NSWorkspace sharedWorkspace]回收URL:]
  3. [NSFileManager垃圾项目AtURL:]
  4. [NSFileManager removeItemAtPath:]
  5. [NSFileManager removeItemAtURL:]

如果能通过阅读这里的解释或苹果官方文档的链接来了解区别,那就太好了。

此外,如果有人知道将文件/非空目录移动到垃圾桶的通用方法,那就太好了。

  1. [[NSWorkspace sharedWorkspace]performFileOperation:NSWorkspaceRecycleOperation]

这是不推荐使用的,从OS X 10.11开始,所以使用它没有意义

  1. [[NSWorkspace sharedWorkspace]回收URL:]

这可能就是你想要的。它是异步的,所以当文件被移到垃圾桶时,应用程序可以继续运行。

  1. [NSFileManager垃圾项目AtURL:]

这与选项2类似,但它是同步的,一次只处理一个文件。

  1. [NSFileManager removeItemAtPath:]

这不会丢弃文件,而是会立即永久删除它。

  1. [NSFileManager removeItemAtURL:]

这与选项4类似,只是使用file://URL而不是路径。当您已经有了URL而不是路径时,会更方便。

NSWorkspace和NSFileManager的参考页很好地涵盖了这些方法之间的所有差异。


下面是一个快速示例,它使用recycleUrls:删除名为"的文件或文件夹;垃圾"在用户的桌面上:

- (IBAction)deleteJunk:(id)sender {
    NSFileManager *manager = [NSFileManager defaultManager];
    NSURL *url = [manager URLForDirectory:NSDesktopDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; // get Desktop folder
    url = [url URLByAppendingPathComponent:@"Junk"]; // URL to a file or folder named "Junk" on the Desktop
    NSArray *files = [NSArray arrayWithObject: url];
    [[NSWorkspace sharedWorkspace] recycleURLs:files completionHandler:^(NSDictionary *newURLs, NSError *error) {
        if (error != nil) {
            //do something about the error
            NSLog(@"%@", error);
        }
        for (NSString *file in newURLs) {
            NSLog(@"File %@ moved to %@", file, [newURLs objectForKey:file]);
        }
    }];
}

最新更新