在 Cocoa上看起来有很多方法可以将文件/文件夹目录移动到垃圾箱: [[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation] [[NSWorkspace sharedWorkspace] recycleURLs:] [NSFileManager trash
> [[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation]
> [[NSWorkspace sharedWorkspace] recycleURLs:]
> [NSFileManager trashItemAtURL:]
> [NSFileManager removeItemAtPath:]
> [NSFileManager removeItemAtURL:]
通过阅读此处的解释或官方Apple文档的链接,了解区别是很好的.
此外,如果有人知道将文件/非空目录移动到垃圾箱的通用方法,那么很高兴知道.
> [[[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]);
}
}];
}
