1

我有一个非常标准的设置。我有一个 UIViewController 来处理用户交互和一个运行时间较长的 NSThread,它在 UI 控制器出现时执行实际工作。我遇到的一个问题是当我想取消 NSThread 时。标准的 NSThread 语义没问题。我希望线程完成,清理自己(以便它释放对我的 UIViewController 的引用),然后弹出 UIViewController。所以我的代码看起来像这样:

在 NSThread 选择器中:

-(void) nsThreadWork
{
  // do work here
  @synchronized(self)
  {
    [nsThreadInstance release];
    nsThreadInstance = nil;
  }
}

在产生线程的 UIViewController 中:

 -(void) startThread    
 {
   nsThreadInstance = [[NSThread alloc] initWithTarget:self 
                                        selector:@(nsThreadWork) ...];
   [nsThreadInstance start];
   [nsThreadInstance release];
 }

如果我想取消:

// assume that this will be retried until we can execute this successfully.
-(void) cancelBackgroundOpAndPopViewController
{
  @synchronized(self)
  {
    if (nsThreadInstance == nil)
    { 
        [self popViewController];
    }
  }
} 

我怀疑这是否正确。问题是,UI 元素只能从主线程中操作。如果我在 NSThread 退出之前弹出视图控制器,NSThread 将退出并释放视图控制器,这意味着它将从 NSThread 的上下文中释放,这将导致断言。上面的代码似乎一切正常,但我不明白 runloop 何时释放 NSThread。任何人都可以提供任何见解吗?

4

0 回答 0