Properly move an object to the Trash

a 夏天 提交于 2020-01-11 08:42:42

问题


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:


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

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:]

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:]

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.

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


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


来源:https://stackoverflow.com/questions/34034638/properly-move-an-object-to-the-trash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!