zoukankan      html  css  js  c++  java
  • GCD11: 创建计时器

    你想重复的执行一个特定任务,这个任务具有一定的延时。 
     
    1.例如:只要你的程序在运 行,你想每秒钟更新一次屏幕中的视图:
    - (void)paint:(NSTimer *)paramTimer{
        NSLog(@"Painting");
    }
    - (void)startPainting{
        self.paintingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(paint:) userInfo:nil repeats:YES];
    }
    - (void)stopPainting{
        if (self.paintingTimer != nil) {
            [self.paintingTimer invalidate];//invalidate[ɪn'vælɪdeɪt]使无效无价值
        }
    }
    - (void)applicationWillResignActive:(UIApplication *)application {
        [self stopPainting];
    }
    - (void)applicationDidBecomeActive:(UIApplication *)application {
        [self startPainting];
    }
      一旦你调用了这样的函数:scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:计时器会变成一个被调度的计时器,就会根据你的请求触发事件。
      一个被调度的计时器也就是这个计时器被添加到了一个事件处理循环中。
      稍后将通过一个例子来演示:创建一个没有被调度的计时器,然后手动在程序的主事件处理循环中调度它。
      这里有多种方法来创建、初始化和调度计时器。最简单的方法就是使用 NSTimer 的类方法 scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:,下面是该方法的参数介绍: 

    interval等待秒数  target接收事件的目标对象  selector目标对象里响应事件的方法 userInfo可传递信息,包含在传递的计时器中 repeat是否重复

      可以使用 NSTimer 的实例方法 invalidate 来停止和释放计时器。这不仅仅会释放计时器, 也会释放计时器拥有的对象(例如userInfo的对象)

     2.

    你也可以使用其他的方法来创建被调度的计时器。NSTimer 的类方法 scheduledTimerWithTimeInterval:invocation:repeats:就是其中之一: 
    - (void)startPainting{
        //2.
        /* Here is the selector that we want to call */
        SEL selectorToCall = @selector(paint:);
        //转成方法签名?Signature签名  instance实例
        NSMethodSignature *methodSignature = [[self class]instanceMethodSignatureForSelector:selectorToCall];
        //??
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
        [invocation setTarget:self];
        [invocation setSelector:selectorToCall];
        /* start a scheduled timer now*/
        self.paintingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 invocation:invocation repeats:YES];
        
    }
     
    3.如果你想要在程序中,手动的在某一个确定时间点调度计时器,可以使用 NSTimer 的类方法 timerWithTimeInterval:target:selector:userInfo:repeats:,当你准备好的时 候,可以把计时器添加到事件处理循环中: 
    - (void) startPainting{
       self.paintingTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(paint:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:self.paintingTimer forMode:NSDefaultRunLoopMode];
    }
  • 相关阅读:
    sprintf与snprintf
    风雨20年:我所积累的20条编程经验
    istream_iterator, ostream_iterator,copy以及文件序列化
    [转载]关于C++,我觉得好的设计法则
    如何高效地管理时间
    B站上适合程序员的学习资源【赶紧收藏!】
    Redis和Memcached的区别
    Swoole的多进程模块
    Mac OS 查看 ip 地址及 DHCP 各 addr 含义
    mac将phpstorm 从主屏移动到副显示器(解决)
  • 原文地址:https://www.cnblogs.com/safiri/p/4080743.html
Copyright © 2011-2022 走看看