【问题标题】:Asynchronously run an NSThread, but with a delegate?异步运行 NSThread,但使用委托?
【发布时间】:2011-11-15 14:46:09
【问题描述】:

我想在新线程上启动一个守护进程,因为我的程序在等待来自守护进程的输入时不会锁定,但我需要一种方法让主程序从守护进程获取信息。我已经使用 NSThread 触发了一个新线程,但我不知道如何将委托与 NSThread 一起使用。

关于更多上下文,我正在为 Quartz Composer 开发一个自定义补丁,该补丁将从网络接收数据。这个想法是第二个线程可以运行守护程序,并且在每一帧上,当守护程序线程接收到新数据时,我会从委托方法设置的 ivar 中获取新数据。在此期间,组合运行与没有中断。

我可以用 NSThread 做到这一点吗?有没有更好的方法我应该看看?

【问题讨论】:

    标签: objective-c delegates nsthread quartz-composer


    【解决方案1】:

    您可能还想考虑使用操作队列 (NSOperation) 或调度队列 (GCD) 来代替 NSThread。

    如果您还没有,请查看 Apple 的 Concurrency Programming Guide;他们确实推荐基于队列的方法,而不是显式创建线程。

    【讨论】:

      【解决方案2】:

      编辑:如果您希望委托回调发生在主线程上,请使用以下模式: [委托 performSelectorOnMainThread:@selector(threadDidSomething:) withObject:self waitUntilDone:NO]

      给你。我相信这是不言自明的,但如果不是,请告诉我。请注意:我只是根据API编写了这段代码,还没有测试过,请谨慎。

      @protocol ThreadLogicContainerDelegate <NSObject>
      - (void)threadLogicContainerDidStart:(ThreadLogicContainer*)theThreadLogicContainer;
      - (void)threadLogicContainerDidFinish:(ThreadLogicContainer*)theThreadLogicContainer;
      @end
      
      @interface ThreadLogicContainer
      
      - (void)doWorkWithDelegate:(id<ThreadLogicContainerDelegate>)delegate;
      
      @end
      
      @implementation ThreadLogicContainer
      
      - (void)doWorkWithDelegate:(id<ThreadLogicContainerDelegate>)delegate
      {
          @autoreleasepool
          {
              [delegate threadLogicContainerDidStart:self];
      
              // do work
      
              [delegate threadLogicContainerDidFinish:self];
          }
      }
      
      @end
      
      
      @interface MyDelegate <ThreadLogicContainerDelegate>
      @end
      
      @implementation MyDelegate
      - (void)threadLogicContainerDidStart:(ThreadLogicContainer*)theThreadLogicContainer
      {}
      - (void)threadLogicContainerDidFinish:(ThreadLogicContainer*)theThreadLogicContainer
      {}
      @end
      

      示例用法:

      ThreadLogicContainer* threadLogicContainer = [ThreadLogicContainer new];
      [NSThread detachNewThreadSelector:@selector(doWorkWithDelegate:)
                               toTarget:threadLogicContainer
                              withObject:myDelegate];
      

      参考:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html

      【讨论】:

        猜你喜欢
        • 2022-01-25
        • 2017-06-23
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-27
        • 1970-01-01
        相关资源
        最近更新 更多