NSTimer的一些注意事项

由于最近面试经常有人问到关于NSTimer的一些问题,所以自己整理了一下记录了一些关键的问题

1 NSTimer为什么有会造成线程堵塞,如何解决

NSTimer是加到当前的runloop中的,就是main runloop,模式是NSDefaultRunLoopMode,而mian runloop是负责主线程事件的,如果主线程有复杂的运算,那么timer就会被堵塞导致计时不准确

解决:1 使用NSRunLoopCommonModes模式,将计时器加到其中比如

self.timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(addTime) userInfo:nil repeats:YES];
 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
   2 开辟子线程,使用子线程的runloop  

 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
     [thread start];
- (void)newThread
{
    @autoreleasepool
   {
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(addTime) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] run];
    }
 }
    3 如果NSTimer一般使用一次不循环用的话,使用 dispatch_after 延时加载,等主线程界面更新再加载计时器
    4 或者使用多线程GCD

2 NSTimer为什么有时不会走dealloc,如何停止NSTimer

timer对象会对object拥有一个强引用,如果object是self,那么self就被timer retain,如果timer一直不invalidated,那么dealloc就一直不会被调用

解决办法: 在viewWillDisappear的时候invalidateNSTimer对象

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [timer invalidate];
}

       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值