Cocoa-UI:延迟performSelector ....延迟

时间:2011-11-09 08:34:37

标签: multithreading macos cocoa selector delay

上下文

在我的Mac应用程序上,当我点击列表项时,会向在背景中执行某些操作的对象发送通知,而在UI上则有等待消息。 所有这些都发生在一个窗口中,您可以通过“关闭”按钮退出。发送通知时,默认情况下禁用该按钮。

我想要做的是一个超时功能,允许用户在几分钟后退出此窗口,从而启用关闭按钮。

代码

- (IBAction)onChangeOperator:(id)sender
{
    [self performSelector:@selector(timerFired:) withObject:nil afterDelay:2.0];
    ....
    ....
    //takes time
    ....
}

-(void) timerFired:(NSTimer *) theTimer {
[close_button setEnabled:YES];
}

问题: 在onChangeOperator完成之前,该按钮才会启用,而我希望在选择器被触发后立即启用它。

我认为这是一个线索,但我无法弄明白。

1 个答案:

答案 0 :(得分:2)

从文档中performSelector:withObject:afterDelay:

  

在延迟后使用默认模式在当前线程上调用接收器的方法。

因此当前线程仍然被阻止。您应该在onChangeOperator上在新线程上运行昂贵的操作:

- (IBAction)onChangeOperator:(id)sender 
{     
    [self performSelector:@selector(timerFired:) withObject:nil afterDelay:2.0];
    [self performSelectorInBackground:@selector(doUpdates) withObject:nil];
}

-(void) timerFired:(NSTimer *) theTimer 
{ 
    [close_button setEnabled:YES]; 
} 

-(void)doUpdates
{
    .... stuff that takes time....
}