IOS系列——NStimer

时间:2023-03-09 19:02:20
IOS系列——NStimer

Timer经常使用的一些东西

1. 初始化

 timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime:) userInfo:nil <span style="font-family: Arial, Helvetica, sans-serif;"> repeats:YES];</span>

2.timer 立即运行

[tiemr fire];

假设在初始化的时候不加这一句代码 ,timer也立即回运行

3. timer 失效

[timer invalidate];<pre name="code" class="html">timer = nil;    //timer失效的时候 ,最好要置空

这个失效之后 是不能又一次使用这个timer的,也就相当于是timer无用了。想继续用timer仅仅能又一次初始化timer 在用

4.timer 暂停

[timer setFireDate:[NSDate distantFuture]];

5.timer 暂停之后又一次開始

[timer setFireDate:[NSDate distantPast]];

6.timer 方法传參

传递的參数是一个id类型,我们一般吧全部的传递參数都放到NSdictionary里面去

    NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%i",animIndexPath] forKey:@"animIndexPath"];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime:) userInfo:dic repeats:YES];

在timer运行的方法里面

-(void)changeTime:(NSTimer *)tme{

    int soundLength = [[[tme userInfo] objectForKey:@"animIndexPath"] intValue];
}
}

这样就能够拿到传递过来的參数

7.推断timer是否在执行

if ([timer isValid]) {
[timer invalidate];
timer = nil;
}