【问题标题】:stop and restart a method停止并重新启动方法
【发布时间】:2011-11-29 17:27:48
【问题描述】:

我必须停止并重新启动一个需要 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 和方法开始(因此打印开始日志和结束日志)。如果我在打印NSLog 之前单击链接的UIButton,则该方法必须停止。这可能吗?

【问题讨论】:

  • 那你为什么不用延迟为0的performSelector:afterDelay:呢?
  • cancelPreviousPerformRequestWithTarget 似乎只取消了一个方法的启动。所以如果这个方法已经启动,我不能停止并重新启动执行。例如,在我的代码中,如果我尝试在使用 cancelPreviousPerformRequestWithTarget 在开始和结束 nslog 之间执行时停止,则始终打印 End nslog。

标签: iphone objective-c multithreading methods


【解决方案1】:

您需要使用后台任务。我建议子类化并使用 NSOperation 并在 main 的正文中检查 isCancelled。请参阅 Apple 关于使用 NSOperation and NSOperationQueue 的文档。

【讨论】:

  • 我在下面添加了评论,这里几乎相同。这种情况下的问题是ui干预,在后台线程中我无法在ui中操作(这是执行时间的很大一部分)
  • 正确,因此您需要将结果/反馈发布到主线程以在 UI 中显示。
【解决方案2】:

好吧,我通常将线程分成 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

【讨论】:

  • 我试图将我的图形计算和 ui 修改划分为适合您的 3 部分理念,问题是关于 ui 干预的大部分执行(以及大部分执行时间)在主线程上。因此,在除法之后,如果我在 -(void)finish:(id)sender 方法中单击“停止按钮”,我会产生相同的效果,直到这段代码结束,我才能停止任何事情。跨度>
猜你喜欢
  • 2013-06-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多