停止并重新启动方法

时间:2011-11-29 17:27:49

标签: iphone objective-c multithreading methods

我必须停止并重新启动一个需要1到2秒才能执行的简单方法。如何实现这一目标?我已经尝试[NSObject cancelPreviousPerformRequestsWithTarget:self],但它只能在延迟后使用performselector。我也尝试创建一个新线程,但它似乎不起作用......

这是我的方法:

-(IBAction)MyMethod
{   
    NSLog(@"start");

    //Here is the code that takes time to execute. It regards UI intervention,graphic calculation, x and y position etc.

    NSLog(@"end");
}

我想要这样的效果:点击链接的UIButton和方法start(所以打印开始日志和结束日志)。如果在打印UIButton之前单击链接的NSLog,则必须停止该方法。这可能吗?

2 个答案:

答案 0 :(得分:2)

您需要使用后台任务。我建议继承并使用NSOperation并在isCancelled的正文中检查main。请参阅Apple有关使用NSOperation and NSOperationQueue

的文档

答案 1 :(得分:0)

嗯,用线程来做这件事我通常做的是把事情分成3个部分:

  • 开始。
  • 的处理。
  • 光洁度。

它看起来像这样:

-(void)start:(id)sender{
    //prepare everything and anything
    [NSThread detachNewThreadSelector:@selector(processing:) toTarget:self withObject:nil];
}

-(void)processing:(id)sender{
    //Perform all your calculations, you can't modify UI elements here

    [self performSelectorOnMainThread:@selector(finish:) withObject:nil waitUntilDone:NO];
}

-(void)finish:(id)sender{
    //Wrap everything up and do any modifications to the UI
}

现在,要取消这个,您可以添加使用:

  

取消先前注册的请求   performSelector:withObject:afterDelay:

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument