NSTimer定时器的简单总结

NSTimer类是我们经常要用到的一个类库,它可以实现一个简单的定时器功能。

NSTimer的初始化:

1.添加一个每0.1s循环一次的NSTimer

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(go) userInfo:nil repeats:YES];

-(void)go
{
    NSLog(@"%@",[NSThread currentThread]);
}

2.使用NSInvocation添加调用的方式来创建NSTimer

在ios中有两种方式来直接调用某个对象的消息,第一种是NSInvocation,第二种是performSelector:withObject:

NSInvocation的优势是在参数大于2或者需要返回值处理的时候来使用

SEL myselector = @selector(go);//创建一个函数签名
    NSMethodSignature *sig = [ViewController instanceMethodSignatureForSelector:myselector];//通过签名初始化
    NSInvocation *myinvo = [NSInvocation invocationWithMethodSignature:sig];//初始化NSInvocation
    int a = 1;
    [myinvo setArgument:&a atIndex:2];//设置参数的Index 需要从2开始,因为前两个被selector和target占用
    [myinvo setTarget:self];//设置target
    [myinvo setSelector:myselector];//设置调用函数
    [myinvo invoke];//启动
    [NSTimer scheduledTimerWithTimeInterval:1.0 invocation:myinvo repeats:YES];

-(void)go
{
    NSLog(@"%@",[NSThread currentThread]);
}

3.标准添加,通过Runloop的方式来添加

  NSRunLoop *myloop = [NSRunLoop currentRunLoop];//初始化一个runloop
  NSTimer *timer = [[NSTimer alloc]initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:1.0] interval:0.1 target:self selector:@selector(go) userInfo:nil repeats:YES];//设置NSTimer
  [myloop addTimer:timer forMode:NSDefaultRunLoopMode];//将timer添加到runloop上

 4.定时器的开启,停止和消失

    [timer setFireDate:[NSDate distantPast]];//开启定时器
    [timer setFireDate:[NSDate distantFuture]];//关闭定时器
    [timer invalidate];//取消定时器--永久停止

 

原文地址:https://www.cnblogs.com/moxuexiaotong/p/4967863.html