如何-performSelector:withObject:afterDelay:work? [英] How does -performSelector:withObject:afterDelay: work?

查看:158
本文介绍了如何-performSelector:withObject:afterDelay:work?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在工作的假设 -performSelector:withObject:afterDelay:不使用线程,但调度一个事件在当前线程以后的日期触发。这是正确的吗?

I am currently working under the assumption that -performSelector:withObject:afterDelay: does not utilize threading, but schedules an event to fire at a later date on the current thread. Is this correct?

更多,特别是:

- (void) methodCalledByButtonClick {
  for (id obj in array) {
    [self doSomethingWithObj:obj];
  }
}

static BOOL isBad = NO;
- (void) doSomethingWithObj:(id)obj {
  if (isBad) {
    return;
  }
  if ([obj isBad]) {
    isBad = YES;
    [self performSelector:@selector(resetIsBad) withObject:nil afterDelay:0.1];
    return;
  }
  //Do something with obj
}

- (void) resetIsBad {
  isBad = NO;
}

是否保证 -resetIsBad 将不会被调用,直到 -methodCalledByButtonClick 返回,假设我们在主线程上运行,即使 -methodCalledByButtonClick

Is it guaranteed that -resetIsBad will not be called until after -methodCalledByButtonClick returns, assuming we are running on the main thread, even if -methodCalledByButtonClick takes an arbitrarily long time to complete?

推荐答案

com / iphone / library / documentation / Cocoa / Reference / Foundation / Classes / NSObject_Class / Reference / Reference.html#// apple_ref / occ / instm / NSObject / performSelector:withObject:afterDelay:rel =nofollow noreferrer> docs

From the docs:



上调用接收器的方法当前线程

讨论进一步:

此方法设置一个定时器,在当前
线程的运行循环中执行
aSelector消息。定时器
配置为以默认模式
(NSDefaultRunLoopMode)运行。当定时器
触发时,线程尝试将
从运行循环的消息出队,
执行选择器。如果
运行循环正在运行,并且在
默认模式下,它将成功;否则,定时器
等待,直到运行循环处于
默认模式。

This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the default mode (NSDefaultRunLoopMode). When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in the default mode; otherwise, the timer waits until the run loop is in the default mode.

回答你的第二个问题。 是,确保,即使在调用 performSelector 时当前线程正在执行时的延迟也较短。当线程返回到运行循环并退出选择器时,您将从 methodCalledByButtonClick 返回。

From this we can answer your second question. Yes, it's guaranteed, even with a shorter delay since the current thread is busy executing when performSelector is called. When the thread returns to the run loop and dequeues the selector, you'll have returned from your methodCalledByButtonClick.

这篇关于如何-performSelector:withObject:afterDelay:work?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆