NSTimer,
计时器
,
作用
:
每隔多少秒执行相应的方法
// 创建方法 1
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(start:) userInfo:nil repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:7.0 target:self selector:@selector(stop:) userInfo:nil repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(print:) userInfo:@"ASXD" repeats:YES];
// 创建方法 2
NSDate *fiveDate = [NSDate dateWithTimeIntervalSinceNow:5];
NSTimer *timer2 = [[NSTimer alloc] initWithFireDate:fiveDate interval:1 target:self selector:@selector(start:) userInfo:nil repeats:YES];
每个线程 (thread) 中都有一个事件循环 (NSRunLoop), 来时时判断是否执行某些事件或方法
加入到事件循环中 , 通过 init 方式创建的 timer 不能执行 , 需要加入到 NSRunLoop 中
[[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
[timer2 release];
// 立即执行第一次操作
[timer2 fire];
// 停止计时器
[timer2 invalidate];
// 创建方法 3
NSTimer *timer3 = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(print:) userInfo:nil repeats:YES];
// 添加到主线程的事件循环中
// 创建方法 1
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(start:) userInfo:nil repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:7.0 target:self selector:@selector(stop:) userInfo:nil repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(print:) userInfo:@"ASXD" repeats:YES];
// 创建方法 2
NSDate *fiveDate = [NSDate dateWithTimeIntervalSinceNow:5];
NSTimer *timer2 = [[NSTimer alloc] initWithFireDate:fiveDate interval:1 target:self selector:@selector(start:) userInfo:nil repeats:YES];
每个线程 (thread) 中都有一个事件循环 (NSRunLoop), 来时时判断是否执行某些事件或方法
加入到事件循环中 , 通过 init 方式创建的 timer 不能执行 , 需要加入到 NSRunLoop 中
[[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
[timer2 release];
// 立即执行第一次操作
[timer2 fire];
// 停止计时器
[timer2 invalidate];
// 创建方法 3
NSTimer *timer3 = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(print:) userInfo:nil repeats:YES];
// 添加到主线程的事件循环中
[[NSRunLoop mainRunLoop] addTimer:timer3 forMode:NSDefaultRunLoopMode];