我正在制作一个 macOS 应用程序。我有一个任务(一个脚本),我在 Swift 3 中使用 Process()
运行。当我按下一个按钮(button.State == NSOnState
)时,我会就像任务重复 n 次,并提前终止,直到再次按下按钮 (button.State == NSOffState
)。
我查找了如何重复一项任务,看起来可以使用简单的 for
循环——for i in {1..n}
。
现在,我遇到的问题是似乎无法多次调用任务。当我第二次尝试调用该任务时,控制台出现错误:
[General] task already launched
这是我的代码:
@IBAction func buttonPressed(_ sender: Any) {
let script = "for i in {1..5}; do echo \"hi\"; done; sleep 1"
let task = Process()
task.terminationHandler = self.commandTerminationHandler
task.launchPath = "/bin/bash"
task.arguments = ["-c", script]
if button.state == NSOnState {
task.launch() // launches task
task.waitUntilExit() // waits until task has been completed (about 1 second)
task.terminate() // (should) terminate the task. (The console error occurs with or without this line)
task.launch() // tries launching the task again, but this results in the console error.
print("The task was launched twice")
} else {
// task.terminate()
}
}
我用谷歌搜索了这个错误,找到了 [this][ https://forums.macrumors.com/threads/nstask-not-terminating.1617855/#post-17677541] :
The error isn't that the task is still running. It's that the task has already run and completed, and can't be started again. You'll need to create a new NSTask object to run the task again.
所以我需要制作一个新的 NSTask
(或 Swift 3 的 Process
)并不断制作新的以永远重复代码。这听起来很复杂(好像我正在使用一种变通方法)并且可能效率很低。
有没有更好的方法在 Swift 3 中重复一个过程?
为了完整起见,我还想提一下,我考虑过在 script
中直接使用 for i in {1..n} do ... done
>。这有一个问题:
- 看起来不可能在再次按下按钮时停止任务。这是因为如果我运行
task.terminate()
,我会收到错误“任务未启动”。我可以停止它的唯一方法是在我的终端中运行killall bash
,这似乎不是一个好的解决方案。要在 Xcode 中执行此操作,我需要创建一个进程以使用 bash 终止 bash...这很奇怪。
最佳答案
我遇到了同样的问题。我在网上遇到的一个潜在修复方法是在终止任务后将任务设置为 nil
,然后在再次运行之前重新分配参数,例如路径、参数等。然而,这只能在 Objective C 中完成; Swift 对 nil
有非常严格的规定(并且可能有充分的理由)。
关于swift - 在 Swift 3 中重复 Process() n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45414849/