【问题标题】:Can I start a thread by pressing a button in a cocoa interface and keep using interface while thread runs?我可以通过按下可可界面中的按钮来启动线程并在线程运行时继续使用界面吗?
【发布时间】:2009-08-04 04:11:31
【问题描述】:

我有一个 Cocoa 界面。当我按下按钮时,我想处理一些数据,但我想在界面工作时继续使用它。我想唯一的解决方案是 NSThread。如果 IBAction 方法产生线程,现在是否会有锁定机制阻止我从 IBAction 方法返回?

【问题讨论】:

  • 我遵循了来自softpixel.com/~cwright/programming/threads/threads.cocoa.php 的示例,但这使用了一个 + 函数,它阻止我与对象进行通信。我声明了一些用作代理的全局变量和指针,它可以工作,但是调用 coreplot 函数会使事情变慢,并且在线程结束之前我的动画中没有任何刷新。我尝试使用 - 函数但没有任何反应,它甚至不响应断点。我想我会看看下面的建议

标签: objective-c cocoa multithreading user-interface asynchronous


【解决方案1】:

不,没有锁定机制。新线程将启动,当前线程将继续。除了NSThread,您可能还想查看performSelectorInBackground:withObject:NSOperation

【讨论】:

    【解决方案2】:

    看看NSOperationNSOperation 是为数不多的可可类之一,它必须被子类化才能有用。通过将delegate 属性添加到您的NSOperation 子类,您可以在操作完成时收到通知。此外,您可以添加 userInfo 属性以允许操作将任意数据传回委托

    @implementation MyNSOperationSubclass
    
    -(void)main
    {
        //do operation here
    
    
    
        //operationResult is used to report back to the delegate. operationResult could include a userInfo key so that the delegate can have some data passed back, or an error key to indicate success of the operation.
        NSDictionary *operationResult; 
    
    
        //Some checks to ensure that the delegate implements operationHasFinished: should be added.
        //waitUntilDone: YES locks the main thread
        [[self delegate] performSelectorOnMainThread:@selector(operationHasFinished:)     withObject:operationResult waitUntilDone: YES];
    
    }
    
    @end
    

    【讨论】:

    • 委托是否能够在其仍在处理时发送消息,以便我可以在线程处理数据时为我的界面设置动画?
    • 是的。 NSOperation 封装了线程。因此,您的 NSOperation 子类执行的处理不会干扰您的主线程(或任何其他线程)。 NSOperation 对主线程的唯一影响是在它调用 performSelectorOnMainThread: 时,但这是设计使然,也是期望的行为。
    【解决方案3】:

    对可可了解不多,但启动一个新线程以在后台处理某些内容,同时保持 UI 线程空闲以获取用户输入(从而防止 UI 冻结)是解决您遇到的问题的最广泛使用的技术提到。两个线程将一起工作(同时),程序员必须处理同步问题(如果有的话)。毫无疑问,您应该继续使用该技术。

    谢谢, 苏拉布

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      相关资源
      最近更新 更多