• oc中定时器的基本使用


     // 时间间隔 调用的对象  调用的方法 用户信息 是否循环

    1    [NSTimer scheduledTimerWithTimeInterval:1
    2                                      target:self
    3                                    selector:@selector(timerAction:)
    4                                    userInfo:@"lidongji"
    5                                     repeats:YES];

    //这个方法是在定时的时间内要做的事(功能)

    1 - (void)timerAction:(NSTimer *)timer {
    2     _count++;
    3     NSLog(@"计时:%ld", _count);
    4     if (_count == 10) {
    5         NSLog(@"%@Bomb了",timer.userInfo);
    6         //终止了我们的定时器
    7         [timer invalidate];
    8     }
    9 }

    //下面的代码必须要写,不然程序只执行一次(一般写在.main文件末尾)

     //让程序保持活跃状态

         1 [[NSRunLoop currentRunLoop] run]; 

     

    调用一次计时器方法:

    1. myTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:NO];  
    2. //不重复,只调用一次。timer运行一次就会自动停止运行  

    重复调用计时器方法:

    1. timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(function:) userInfo:nil repeats:YES];  
    2. //1秒运行一次function方法。  
    3. 注意:将计数器的repeats设置为YES的时候,self的引用计数会加1因此可能会导致self(即viewController)不能release,所以,必须在viewWillAppear的时候,将计数器timer停止,否则可能会导致内存泄露。
    4. 停止timer的运行,但这个是永久的停止:(注意:停止后,一定要将timer赋空,否则还是没有释放。不信?你自己试试~
    5. //取消定时器  
    6. [timer invalidate];  
    7. timer = nil;

    要想实现:先停止,然后再某种情况下再次开启运行timer,可以使用下面的方法:

    首先关闭定时器不能使用上面的方法,应该使用下面的方法:

     

    1. //关闭定时器  
    2. [myTimer setFireDate:[NSDate distantFuture]];  

     

    然后就可以使用下面的方法再此开启这个timer了:

     

    1. //开启定时器  
    2. [myTimer setFireDate:[NSDate distantPast]];  

     

    例子:比如,在页面消失的时候关闭定时器,然后等页面再次打开的时候,又开启定时器。

    (主要是为了防止它在后台运行,暂用CPU)可以使用下面的代码实现:

     

    1. //页面将要进入前台,开启定时器  
    2. -(void)viewWillAppear:(BOOL)animated  
    3. {  
    4.     //开启定时器  
    5.     [scrollView.myTimer setFireDate:[NSDate distantPast]];  
    6. }  
    7.   
    8. //页面消失,进入后台不显示该页面,关闭定时器  
    9. -(void)viewDidDisappear:(BOOL)animated  
    10. {  
    11.     //关闭定时器  
    12.     [scrollView.myTimer setFireDate:[NSDate distantFuture]];  
    13. }  
  • 相关阅读:
    多线程--ThreadLocal类
    常用开发类库支持--UUID及空值处理Optional
    国际化的程序实现及其原理
    浅析java设计模式(一)----异构容器,可以存储任何对象类型为其他类提供该对象
    使用批处理命令注册运行mysql数据库,无需注册mysql服务,可以在任意电脑登录使用
    计算机中位、字长、字的区别
    SQL Server用户自定义数据类型
    简单的回合制小游戏
    单链表创建、删除、查找、插入之C语言实现
    LeetCode-905 Sort Array By Parity Solution (with Java)
  • 原文地址:https://www.cnblogs.com/qq1871707128/p/6014732.html
Copyright © 2020-2023  润新知