- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
date: 第一次 fire 时间
interval:重复fire的时间间隔,适用于repeats为YES
target:表示发送的对象,如self
aSelector:方法选择器,在时间间隔内,选择调用一个实例方法
userInfo:id类型,可以为空。可以在aSelector中强转回之前传入的类型。
repeats:当YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。
/**
* 启动一个NSTimer
*/
-(void)timerTest
{
NSNumber* testValue = [NSNumber numberWithInt:100];
NSDate* fireDate = [[NSDate alloc] initWithTimeIntervalSinceNow:5]; //5s 后 第一次 fire
NSTimer* testTimer = [[NSTimer alloc] initWithFireDate:fireDate interval:5 target:self selector:@selector(timerSelector:) userInfo:testValue repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:testTimer forMode:NSDefaultRunLoopMode];
}
/**
* NSTimer 执行函数
*/
-(void)timerSelector:(id)sender
{
int value = [(NSNumber*)[sender userInfo] intValue]; //取回之前传入的数据
NSLog(@"timerTest value: %d", value);
//略...
}
---- 参考内容:
-----
initWithFireDate:interval:target:selector:userInfo:repeats:
Initializes a new NSTimer object using the specified object and selector.
- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
Parameters
date
The time at which the timer should first fire.
seconds
For a repeating timer, this parameter contains 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
Custom 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.
Return Value
The receiver, initialized such that, when added to a run loop, it will fire at date and then, if repeats is YES, every seconds after that.
Discussion
You must add the new timer to a run loop, using addTimer:forMode:. Upon firing, the timer sends the message aSelector to target. (If the timer is configured to repeat, there is no need to subsequently re-add the timer to the run loop.)
Availability
- Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSTimer.h