异步运行 NSThread,但使用委托?
我想在新线程上启动一个守护进程,以便我的程序在等待守护进程的输入时不会锁定,但我需要一种方法让主程序从守护进程获取信息。我已经使用 NSThread 来启动一个新线程,但我不知道如何将委托与 NSThread 一起使用。
对于更多上下文,我正在为 Quartz Composer 开发一个自定义补丁,它将从网络接收数据。这个想法是,第二个线程可以运行守护程序,并且在每个帧上,当守护程序线程接收到新数据时,我会从委托方法设置的 ivar 中获取新数据。一直以来,组合都与没有中断。
我可以用 NSThread 做到这一点吗?我应该看看有更好的方法吗?
I want to launch a daemon on new thread, to my program doesn't lock up while waiting for input from the daemon, but I need a way for the main program to get information back from the daemon. I've used NSThread to fire off a new thread, but I don't see how to use a delegate with NSThread.
For more context, I'm working on a custom patch for Quartz Composer that will receive data from the network. The idea is that a second thread could run the daemon, and on each frame, I'd grab the new data from an ivar set by a delegate method when the daemon thread received new data.. all the while, the composition runs along with no interruption.
Can I do this with NSThread? Is there a better way I should be looking at?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能还想考虑使用操作队列 (NSOperation) 或调度队列 (GCD) 而不是 NSThread。
如果您还没有阅读过 Apple 的并发编程指南< /a>;他们确实推荐基于队列的方法而不是显式的线程创建。
You might also want to consider using operation queues (NSOperation) or dispatch queues (GCD) instead of NSThread.
If you haven't already, take a look at Apple's Concurrency Programming Guide; they're really recommending the queue-based approach instead of explicit thread creation.
编辑:如果您希望委托回调发生在主线程上,请使用以下模式:
[delegate PerformSelectorOnMainThread:@selector(threadDidSomething:) withObject:self waitUntilDone:NO]
开始吧。我相信这是不言自明的,但如果不是,请告诉我。请注意:我只是根据API编写了这段代码,但没有测试过,所以要小心。
示例用法:
参考: http ://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html
Edit: If you want the delegate callbacks to occur on the main thread, use this pattern:
[delegate performSelectorOnMainThread:@selector(threadDidSomething:) withObject:self waitUntilDone:NO]
Here you go. I believe this is self-explanatory, but if not, just let me know. Please note: I just wrote this code based on the API, but have not tested it, so take caution.
Sample usage:
reference: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html