当前位置:  开发笔记 > IOS > 正文

将对象正确移动到废纸篓

如何解决《将对象正确移动到废纸篓》经验,为你挑选了1个好方法。

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

    [[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation]

    [[NSWorkspace sharedWorkspace] recycleURLs:]

    [NSFileManager trashItemAtURL:]

    [NSFileManager removeItemAtPath:]

    [NSFileManager removeItemAtURL:]

通过阅读此处的解释或官方Apple文档的链接,了解区别是很好的.

此外,如果有人知道将文件/非空目录移动到垃圾箱的通用方法,那么很高兴知道.



1> Mark Bessey..:

    [[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation]

从OS X 10.11开始,这已被弃用,因此无需使用它.

    [[NSWorkspace sharedWorkspace] recycleURLs:]

这可能是你想要的.它是异步的,因此您的应用程序可以在文件移动到废纸篓时继续运行.

    [NSFileManager trashItemAtURL:]

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

    [NSFileManager removeItemAtPath:]

这不会丢弃文件,它会立即删除它.

    [NSFileManager removeItemAtURL:]

这与选项4类似,只是使用file:// URL而不是路径.当你已经拥有一个URL而不是一个路径时更方便.

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


这是一个快速示例,它使用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]);
        }
    }];
}

推荐阅读
依然-狠幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有