![](/img/trans.png)
[英]What is the correct way of accessing a Swift Delegate from Objective-C?
[英]What is the correct way to open a file from line arguments in an NSDocument application in Swift?
我正在開發一個基於 MacOS Document 的應用程序,它可以打開某種文件類型。 我想做的是為這個應用程序編寫一些 UI 測試,但我想為這些 UI 測試加載一些模擬數據。 據我了解,我實際上應該使用 launchArguments 或 launchEnvironment 變量來加載這個模擬數據。
因此,在我看來,正確的做法是創建一些測試數據文件,並在應用程序啟動時使用以下內容打開這些文件:
let app = XCUIApplication()
app.launchArguments.append("-url")
app.launchArguments.append($PATH)
app.launch()
現在我的問題是,我應該在哪里添加在啟動期間打開文件的代碼? NSDocumentDelegate 是否有我應該重寫的方法? 我應該調用openDocument(withContentsOf:display:completionHandler:)
還是完全設置fileURL
或其他東西?
現在我的應用程序打開最后打開的文件或打開一個新文檔。 我可以嘗試覆蓋makeUntitledDocument(ofType typeName: String)
或func restoreWindow(withIdentifier identifier: NSUserInterfaceItemIdentifier, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Void)
但我不喜歡其中任何一個是正確的選擇。
所以我想我有兩個問題:1)為基於 NSDocument 的應用程序的 UI 測試傳遞模擬數據的正確方法是什么。 2) 使用 line 參數在啟動應用程序時打開文件的正確方法是什么。
1) 為基於 NSDocument 的應用程序的 UI 測試傳遞模擬數據的正確方法是什么?
我要做的是:
1) 要打開一個新文檔,我調用makeUntitledDocument(ofType typeName: String)
。 根本不需要覆蓋它。 然后,您可以根據需要使用此 API 的返回值設置文檔。
2)要打開以前保存的文檔,我確實調用了openDocument(withContentsOf:display:completionHandler:)
使用偽代碼將是這樣的,您可以將任何 URL 與模擬數據一起傳遞:
func openDocument(itemData:ItemData) {
let controller = NSDocumentController.shared
controller.openDocument(withContentsOf: itemData.url, display: true)
{ (_, _, error:Error?) in
if error != nil {
handleError(.unableToOpenDocument(itemData.url))
}
}
}
再一次,沒有必要覆蓋openDocument(withContentsOf:display:completionHandler:)
。
2)使用 line 參數在啟動應用程序時打開文件的正確方法是什么?
我會為此使用 bash 腳本:
open -a $APP_PATH $DOCUMENT_PATH
這將模仿 Finder 的功能,但如果您不喜歡該選項,那么您可以隨時嘗試他們在此問題的答案中提出的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.