zoukankan      html  css  js  c++  java
  • NSTimer的一个误区

    之前的写过一个单例,里面有一个NSTimer。当时写了NSTimer的stop和pause方法。现在突然发现当时写的方法是错误的。现在写出正确的方法。

    -(void)timestart
    {
        dispatch_queue_t queue=dispatch_queue_create("queue1", DISPATCH_QUEUE_SERIAL);
       dispatch_async(queue,^{
                if (!_timer) {
            _timer=[NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(UpdateUI) userInfo:nil repeats:YES];
        }
            [[NSRunLoop currentRunLoop] run];//必须放在定时器创建之后执行
    
        });
    }
    
    错误的暂停方法
    -(void)timepause
    {
    if(_timer.isValid)
    {
      [_timer invalidate];
    }
    }
    
    //为什么这个方法是错误的,今天看了苹果的文档,这个方法是吧timer移除NSRunloop.其实也就是一种销毁,如果你把这个方法作为暂停,下次其实你需要再启动timer,就必须得再调用timer的初始化方法,从逻辑上来说根本就不是暂停。当时的我就是犯了这么一个错误。
    
    
    //正确的方法
    -(void)timepause
    {
        if (!_timer.isValid) {
            return;
        }
        [_timer setFireDate:[NSDate distantFuture]];
    }
    //从暂停到重新运行timer
    -(void)timeresume
    {
        if (!_timer.isValid) {
            return;
        }
        [_timer setFireDate:[NSDate date]];
    }
    //停止方法,将timer移除runloop并且置为nil,在arc模式下timer的内存就会自动被释放
    -(void)timestop
    {
        if (_timer.isValid) {
            [_timer invalidate];
            _timer=nil;
        }
    }

    感觉没啥人会犯这种低级错误,写出来也算是提醒自己吧。

  • 相关阅读:
    Python+Selenium三种等待方法
    Jmeter结果分析_聚合报告
    Linux安装Python3
    翻译Go Blog: 常量
    Go: 复合数据类型slice
    Python创建二维列表的正确姿势
    了解Flask
    urllib3中学到的LRU算法
    了解Prometheus
    《redis 5设计与源码分析》:第二章 简单动态字符串
  • 原文地址:https://www.cnblogs.com/xiaomingtongxue/p/4639746.html
Copyright © 2011-2022 走看看