开发者

Call a method after 5 sec. without NSTimer

I want to call any method OR event after 5 sec开发者_高级运维ond in iphone without using NStimer.


Use performSelector:withObject:afterDelay: method.

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


Or use 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. He explicitly asked for a way to do this without using an NSTimer yet he didn't specify why. 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜