我正在使用第三方框架编写Swift中的命令行应用程序,当套接字接收数据时,该框架(如果我理解正确的话)依赖GCD回调来完成某些操作。为了更好地理解这个框架,我一直在尝试框架的作者编写的一个示例Cocoa应用程序。
因为示例应用程序是Cocoa应用程序,所以run循环是自动处理的。我包含了示例应用程序(MIT license)中的代码片段,以了解其工作原理:
class AppDelegate: NSObject, NSApplicationDelegate {
var httpd : Connect!
func startServer() {
httpd = Connect()
.onLog {
[weak self] in // unowned makes this crash
self!.log($0)
}
.useQueue(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))..。
httpd.listen(1337)
}..。
func applicationDidFinishLaunching(aNotification: NSNotification?) {
startServer()
...
}
}我想将示例应用程序修改为从命令行运行。当我将startServer()函数放入命令行应用程序中时,它会运行,但套接字在打开后立即关闭,并且程序结束执行,退出代码为0。这是预期的行为,因为在Xcode命令行项目中没有run循环,因此程序不知道等待套接字接收数据。
我认为让套接字保持打开并使程序持续运行的正确方法是将主线程放在CFRunLoop中。我已经看过了Apple的文档,除了基本的API参考之外,在Swift中没有任何关于线程的内容。我看过第三方资源,但它们都涉及iOS和Cocoa应用程序中的交替线程。如何正确地实现主线程的CFRunLoop?
发布于 2014-08-05 04:20:49
NSRunLoop Class Reference有一个简单运行循环的示例:
BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);可以翻译成Swift:
var shouldKeepRunning = true // global
let theRL = NSRunLoop.currentRunLoop()
while shouldKeepRunning && theRL.runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture()) { }或者,可能只需调用
dispatch_main()Swift 3.1的更新:
let theRL = RunLoop.current
while shouldKeepRunning && theRL.run(mode: .defaultRunLoopMode, before: .distantFuture) { }或
dispatchMain()发布于 2014-08-05 04:25:43
看起来Martin R的回答应该是有效的,但是我能够通过一个函数调用让套接字保持打开状态。在startServer()函数的末尾,我放入一行代码:
CFRunLoopRun()它起作用了。
https://stackoverflow.com/questions/25126471
复制相似问题