簡體   English   中英

通過Objective-C / Cocoa清空垃圾桶

[英]Empty Trash Bin via Objective-C/Cocoa

我想知道是否有辦法以編程方式清空垃圾桶的內容。 我目前正在刪除位於那里的文件:

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

但是,在我使用此操作后,每次將文件拖到回收站時,系統都會提示我:

您確定要刪除“xxxxxx.xxx”嗎?此項目將立即刪除。 您無法撤消此操作。

這一直持續到我退出或sudo rm -rf垃圾桶。

謝謝!

您可以嘗試使用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];

您可以使用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文檔


從Xcode 7.3開始,如果你用Swift嘗試這個,你會發現鏈接器錯誤,試圖找到在Finder.h中定義的類。 所以你必須創建一個Objective-C包裝器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM