本文介绍了正确将对象移到垃圾箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Cocoa上,似乎有很多方法可以将文件/文件夹目录移动到废纸rash":

It looks like on Cocoa there are many ways to move file/folder-directory to Trash:

  1. [[[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation]
  2. [[[NSWorkspace sharedWorkspace] recycleURLs:]
  3. [NSFileManager trashItemAtURL:]
  4. [NSFileManager removeItemAtPath:]
  5. [NSFileManager removeItemAtURL:]

通过阅读此处的说明或指向苹果官方文档的链接来了解两者之间的区别是很高兴的.

It would be nice to understand what the difference is by either reading an explanation here or a link to the official Apple docs.

如果有人知道将文件/非空目录移动到回收站的通用方法,那将是很高兴的.

Also if someone knows a universal way of moving a file/non-empty directory to Trash, it would be nice to know.

推荐答案

  1. [[[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation]

从OS X 10.11开始不推荐使用,因此没有必要使用它.

This is deprecated, as of OS X 10.11, so no point in using it.

  1. [[[NSWorkspace sharedWorkspace] recycleURLs:]

这可能是您想要的那个.它是异步的,因此在将文件移至回收站时,您的应用程序可以继续运行.

This is probably the one you want. It's asynchronous, so your application can continue to operate while the files are being moved to the trash.

  1. [NSFileManager trashItemAtURL:]

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

This is similar to option 2, but it's synchronous, and only handles one file at a time.

  1. [NSFileManager removeItemAtPath:]

这不会破坏文件,它会立即将其永久删除.

This doesn't trash the file, it deletes it permanently, and immediately.

  1. [NSFileManager removeItemAtURL:]

这与选项4相似,除了使用file://URL而不是路径.当您已经拥有URL路径而不是路径时,会更加方便.

This is just like option 4, except using a file:// URL instead of a path. More-convenient when you already have a URL rathe than a path.

NSWorkspace NSFileManager 很好地涵盖了这些方法之间的所有差异.

The reference pages for NSWorkspace and NSFileManager cover all of the differences between these methods fairly well.

下面是一个快速示例,该示例使用recycleUrls:删除用户桌面上名为"Junk"的文件或文件夹:

Here's a quick sample, which uses recycleUrls: to delete a file or folder named "Junk" on the user's desktop:

- (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]);
        }
    }];
}

这篇关于正确将对象移到垃圾箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 00:57