- [[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation]
This is deprecated, as of OS X 10.11, so no point in using it.
- [[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.
- [NSFileManager trashItemAtURL:]
This is similar to option 2, but it's synchronous, and only handles one file at a time.
- [NSFileManager removeItemAtPath:]
This doesn't trash the file, it deletes it permanently, and immediately.
- [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 rather 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]);
}
}];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…