简体   繁体   English

5 秒后调用一个方法。 没有 NSTimer

[英]Call a method after 5 sec. without NSTimer

I want to call any method OR event after 5 second in iphone without using NStimer.我想在不使用 NStimer 的情况下在 iphone 中 5 秒后调用任何方法或事件。

Use performSelector:withObject:afterDelay: method.使用performSelector:withObject:afterDelay:方法。

[self performSelector:@selector(methodName) withObject:nil afterDelay:5];

Or use GCD:或者使用 GCD:

double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    /* code to be executed on the main queue after delay */
});

The question sounds like a very pointless assignment.这个问题听起来像是一个非常没有意义的任务。 That calls for an equally useless answer:这就需要一个同样无用的答案:

sleep(5);
[self myMethodToCallAfter5Seconds];

Edit: Since people don't seem to like my answer, here are some thoughts:编辑:由于人们似乎不喜欢我的回答,这里有一些想法:

The OP asked for a way to send a message after a delay. OP 要求一种在延迟后发送消息的方法。 He explicitly asked for a way to do this without using an NSTimer yet he didn't specify why.他明确要求一种不使用NSTimer的方法来做到这一点,但他没有具体说明原因。 As there are many ways to send a message after a delay, picking one depends upon the reason why to avoid any specific method.由于延迟后发送消息的方法有很多种,因此选择一种取决于避免使用任何特定方法的原因。 Not knowing the reason for refusing an obvious approach there's only speculation.不知道拒绝明显方法的原因,只有猜测。

One possible situation could be a background thread without a runloop that should await the delay.一种可能的情况是没有运行循环的后台线程应该等待延迟。 Here my (not totally serious) proposal could even be a proper solution when blocking the thread is not an issue.在这里,当阻塞线程不是问题时,我的(不是完全严肃的)建议甚至可能是一个适当的解决方案。 In this scenario neither NSTimer nor performSelector:withObject:afterDelay: could be used.在这种情况下,既不能使用NSTimer也不能使用performSelector:withObject:afterDelay:

I added this answer to highlight the fact that the question makes little sense without giving a reason.我添加了这个答案是为了强调这个问题没有给出理由就没有什么意义。 As my answer fulfills the specification it shows the pointlessness of the question.当我的回答符合规范时,它表明了这个问题的毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM