Set an NSTimer to fire once in the future

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

How do I set up an NSTimer to fire once in the future (say, 30 seconds). So far, I have only managed to set it so it fires immediately, and then at intervals.

回答1:

The method you want to use is:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval) seconds target:(id) target selector:(SEL) aSelector userInfo:(id) userInfo repeats:(BOOL) repeats

with repeats == NO arguments and seconds == 30. This will create the timer and schedule it. It will fire only once, in 30 seconds (and not immediately).



回答2:

You can set the timer with your future date, and set repeats to NO

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval) seconds                                      target:(id) target                                    selector:(SEL) aSelector                                    userInfo:(id) userInfo                                     repeats:(BOOL) repeats


回答3:

Use this class method to schedule timer.

 +(NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds     target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo     repeats:(BOOL)repeats

Parameters
seconds
The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead.
target
The object to which to send the message specified by aSelector when the timer fires. The target object is retained by the timer and released when the timer is invalidated.
aSelector
The message to send to target when the timer fires. The selector must have the following signature:
- (void)timerFireMethod:(NSTimer*)theTimer
The timer passes itself as the argument to this method.
userInfo
The user info for the timer. The object you specify is retained by the timer and released when the timer is invalidated. This parameter may be nil.
repeats
If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
Example

    [NSTimer scheduledTimerWithTimeInterval:2.0              target:self              selector:@selector(targetMethod:)              userInfo:[self userInfo]              repeats:NO];

The timer is automatically fired by the run loop after 2 seconds. Timer Programming Topics



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!