定时器-NSTimer

来源:互联网 发布:纪念册制作软件app 编辑:程序博客网 时间:2024/05/02 06:13

NSTimer属性和常用方法

iOS中每隔一段时间做事情,一般使用两个类

NSTimer(普通应用,时间间隔大)、CADisplayLink(小游戏)


NSTimer叫做“定时器”,它的作用如下
Ø在指定的时间执行指定的任务
Ø每隔一段时间执行指定的任务
Ø
调用下面的方法就会开启一个定时任务

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti  target:(id)aTarget

  selector:(SEL)aSelector

  userInfo:(id)userInfo

  repeats:(BOOL)yesOrNo;

每隔ti秒,调用一次aTargetaSelector方法yesOrNo决定了是否重复执行这个任务

通过invalidate方法可以停止定时器的工作,一旦定时器被停止了,就不能再次执行任务(一般会 timer = nil)。只能再创建一个新的定时器才能执行新的任务

- (void)invalidate;

timer = nil


NSTimer应用

/**
 *  // 添加定时器
 */
- (void)addTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImg) userInfo:nil repeats:YES];
    // 设置定时器的优先级:拿到当前线程所在的消息循环,并且将这个定时器添加到这个消息循环中(定时器两种模式:默认模式和优先级模式)
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/**
 *  // 移除定时器(定时器一旦停止,就不能再次使用,所以nil)
 */
- (void)removeTimer{
    [self.timer invalidate];
    self.timer = nil;
}


0 0