【问题标题】:Properly move an object to the Trash将对象正确移动到废纸篓
【发布时间】:2015-12-02 03:54:39
【问题描述】:

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

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

通过阅读此处的说明或指向 Apple 官方文档的链接来了解区别是什么。

另外,如果有人知道将文件/非空目录移动到废纸篓的通用方法,我很高兴知道。

【问题讨论】:

    标签: macos cocoa directory file-management recycle-bin


    【解决方案1】:
    1. [[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation]

    从 OS X 10.11 开始,它已被弃用,因此没有必要使用它。

    1. [[NSWorkspace sharedWorkspace] recycleURLs:]

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

    1. [NSFileManager 垃圾项AtURL:]

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

    1. [NSFileManager removeItemAtPath:]

    这不会删除文件,它会立即永久删除它。

    1. [NSFileManager removeItemAtURL:]

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

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


    这是一个快速示例,它使用 recycleUrls: 删除用户桌面上名为“Junk”的文件或文件夹:

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

    【讨论】:

    • 1.我需要可以在 10.6+ 中运行的代码。 2. 解决方案 2 是否适用于文件和非空目录?我也会检查这些参考资料。你能放一些示例代码来垃圾目录吗?
    • recycleUrls: 在 OS X 10.6 及更高版本中可用。我在答案中添加了一些示例代码。
    • 我在“NSArray *files = @[url];”这一行遇到错误。谷歌搜索说我需要最新的 LLVM,但我没有。我在 10.6 上使用 XCode 4.2。我如何重写这一行?谢谢。
    • 我把它改成了老式的 Objective-C 符号。希望对您有所帮助。
    • 选项 2 和 3 都接受通配符吗?选项 3 可以发送目录而不仅仅是文件,对吗?选项 3 也是 10.6+,对吧?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多