iOS NSTimer的使用
NSTimer 我们通常会用在背景计算,更新一些数值资料。NSTimer有五种初始化方法:
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
——timerWithTimeInterval这两个类方法创建出来的对象如果不用 addTimer: forMode方法手动加入主循环池或者子线程循环中,将不会循环执行。并且如果不手动调用fire,则定时器不会启动。
在多线程开发中,如果是在子线程中使用定时器,只能使用以上两种方法:
// 开启一个定时器 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 invocation:invo repeats:NO]; [invo setTarget:self]; [invo setSelector:@selector(test)]; // 添加到主循环 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; // 开始循环 [timer fire];
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
——scheduledTimerWithTimeInterval这两个方法默认添加到当前的runloop中,会自动执行,并且自动加入主循环池。
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES]; [timer fire];
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep
——init方法需要手动加入循环池,它会在设定的启动时间启动。
NSTimer *timer = [[NSTimer alloc] initWithFireDate:[NSDate distantPast] interval:1.0 target:self selector:@selector(test) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
添加到主循环或者新开循环的时候,forMode:的选择有两个,如下
- (void)addTimer:(NSTimer *)timer forMode:(NSString *)mode;
DefaultRunLoopMode:当我们执行其他滚动事件时,timer会默认暂时不监听,当滚动结束的时候会,继续监听。
NSRunLoopCommonModes:始终监听滚动事件
参数:
NSTimeInterval:时间间隔
NSInvocation:动态执行对象的方法
repeats:指定是否循环执行,YES将循环,NO将只执行一次。
userInfo: 是指NSTimer携带的用户信息
// 管理定时器的启动和停止
@property (copy) NSDate *fireDate;
// 获取定时器调用的时间间隔
@property (readonly) NSTimeInterval timeInterval;
// ios7之后出来的,用来设置NSTimer的误差
@property NSTimeInterval tolerance NS_AVAILABLE(10_9, 7_0);
// 停止定时器(这个是唯一一个可以将计时器从runloop中移出的方法)
- (void)invalidate;
// 获取定时器是否有效
@property (readonly, getter=isValid) BOOL valid;
// 获取参数信息
@property (readonly, retain) id userInfo;

浙公网安备 33010602011771号