如何退出runloop?

hot*_*aw2 1 swift swift3

所以,我有一个Swift命令行程序:

import Foundation

print("start")

startAsyncNetworkingStuff()

RunLoop.current.run()

print("end")
Run Code Online (Sandbox Code Playgroud)

代码编译没有错误.异步网络代码运行正常,获取其所有数据,打印结果,并最终调用其完成功能.

如何获得完成功能以突破当前的runloop以便打印最后一个"结束"?

添加:

用以下内容替换RunLoop.current.run():

print("start")

var shouldKeepRunning = true

startAsyncNetworkingStuff()

let runLoop = RunLoop.current
while (   shouldKeepRunning
       && runLoop.run(mode:   .defaultRunLoopMode,
                      before: .distantFuture ) ) {
}

print("end")
Run Code Online (Sandbox Code Playgroud)

设置

shouldKeepRunning = false
Run Code Online (Sandbox Code Playgroud)

在异步网络完成功能中仍然不会导致"结束"打印.(这是通过使用print语句包含shouldKeepRunning = false语句来检查的,该语句实际上是打印到控制台).缺什么?

vad*_*ian 9

对于命令行界面,使用此模式并向AsyncNetworkingStuff添加完成处理程序(感谢Rob的代码改进):

print("start")

let runLoop = CFRunLoopGetCurrent()
startAsyncNetworkingStuff() { result in 
   CFRunLoopStop(runLoop)
}

CFRunLoopRun()
print("end")
exit(EXIT_SUCCESS)
Run Code Online (Sandbox Code Playgroud)

请不要使用丑陋的while循环.

  • 丑陋?但建议在Apple的官方文档中:https://developer.apple.com/reference/foundation/runloop/1412430-run (2认同)