【问题标题】:Empty Trash Bin via Objective-C/Cocoa通过 Objective-C/Cocoa 清空垃圾箱
【发布时间】:2011-07-17 02:34:37
【问题描述】:

我想知道是否有办法以编程方式清空垃圾箱的内容。我目前正在使用以下方式删除位于那里的文件:

    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:fileToDelete error:nil];

但是,我使用此操作后,每次将文件拖到垃圾箱时,都会提示以下消息:

您确定要删除 “xxxxxx.xxx”?该项目将被删除 立即地。您无法撤消此操作 行动。

这一直持续到我注销或 sudo rm -rf 垃圾箱。

谢谢!

【问题讨论】:

  • 为什么需要这样做?废纸篓是用户的领域,你的应用不应该真的搞砸它。

标签: objective-c cocoa macos nsfilemanager recycle-bin


【解决方案1】:

您可以使用NSWorkspace 将内容放入垃圾箱,但是删除垃圾箱对于程序来说是一种禁忌,因此您不会找到 API。所以最好的选择是使用 ScriptBridge。

ScriptingBridge.framework 添加到您的构建目标,并使用以下命令为 Finder 生成头文件:

sdef /System/Library/CoreServices/Finder.app/ | sdp -fh --basename Finder

然后你可以让 Finder 提示用户清空回收站:

#import "Finder.h"

FinderApplication *finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.Finder"];

// activate finder
[finder activate];

// wait a moment (activate is not instant), then present alert message
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  [finder emptySecurity:security];
});

有关详细信息,请参阅Scripting Bridge documentation


从 Xcode 7.3 开始,如果您尝试使用 Swift 进行此操作,您将在尝试查找 Finder.h 中定义的类时遇到链接器错误。所以你必须创建一个 Objective-C 包装器。

【讨论】:

  • 是的,如果您的应用是沙盒的,您将需要脚本授权。
  • 但是,如果你的应用是沙盒的,为什么需要清空垃圾箱呢?提出问题。
  • 这是我应用的功能之一
【解决方案2】:

您可以尝试使用 AppleScript 来执行此操作:

NSString* appleScriptString = @"tell application \"Finder\"\n"
                              @"if length of (items in the trash as string) is 0 then return\n"
                              @"empty trash\n"
                              @"repeat until (count items of trash) = 0\n"
                              @"delay 1\n"
                              @"end repeat\n"
                              @"end tell";
NSAppleScript* emptyTrashScript = [[NSAppleScript alloc] initWithSource:appleScriptString];

[emptyTrashScript executeAndReturnError:nil];
[emptyTrashScript release];

【讨论】:

  • 谢谢!有没有办法一次做一个文件?我在回调方法中单独删除文件,并对每个文件执行检查,删除它,然后继续下一个。
  • 它们已经在回收站中了吗?您不能一次清空垃圾箱一个文件。但是,您可能会进行检查,删除文件,然后在完成处理后清空垃圾箱。或者,您可以遍历回收站中的文件并将不想删除的文件移出回收站,但这会适得其反。
猜你喜欢
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
相关资源
最近更新 更多