正确地将对象移至废纸篓 [英] Properly move an object to the Trash

查看:39
本文介绍了正确地将对象移至废纸篓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来在 Cocoa 上有很多方法可以将文件/文件夹目录移动到垃圾箱:

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. [NSFileManagertrashItemAtURL:]
  4. [NSFileManager removeItemAtPath:]
  5. [NSFileManager removeItemAtURL:]

通过阅读此处的解释或指向 Apple 官方文档的链接来了解不同之处会很好.

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. [NSFileManagertrashItemAtURL:]

这类似于选项 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 rather than a path.

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

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

这篇关于正确地将对象移至废纸篓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆