以使用任何对象,并且可以获得正在执行的消息中的对象引用(上面的selector参数)。这里使用字符串,但通常会使用字典或其他集合以支持更加复杂的活动。
参数六:repeats参数表示定时器是发送一次消息,还是根据第2个参数指定的时间间隔重复发送。
NSRunLoop *runLoop=[NSRunLoop currentRunLoop[;
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
10秒钟后,定时器将会开始每隔两秒钟向应用发送task消息。
[timer invalidate];
/**
*定时器小例子
*/
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window=_window;
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification{
NSDate *scheduledTime=[NSDate dateWithTimeIntervalSinceNow:10.0];
NSString *customUserObject=@"To demo userInfo";
NSTimer *timer=[[NSTimer alloc]initWithFireDate:scheduledTime
interval:2
target:self
selector:@selector(task)
userInfo:customUserObject
repeats:YES];
NSRunLoop *runLoop=[NSRunLoop currentRunLoop[;
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
}
-(void)task:(id)sender{
NSTimer *localTimer=(NSTimer *)sender;
NSLog(@"Schedule task has executed with this user info :%@",[localTimer userInfo]);
}
@end
|