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.
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).
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With