• swift 定时器的使用


    在swift中,要使用定时器就需要用到对象NSTimer。通过NSTimer的实例化后,就可以调用fire方法来启用了。

    NSTimer有2个构造函数

    init(timeInterval ti: NSTimeInterval, invocation: NSInvocation!, repeats yesOrNo: Bool) -> NSTimer
    
    init(timeInterval ti: NSTimeInterval, target aTarget: AnyObject!, selector aSelector: Selector, userInfo: AnyObject!, repeats yesOrNo: Bool) -> NSTimer
    

    通过我的实践后,发现这2个构造函数都是假的,基本上不能使用。第一个构造函数的invocation参数貌似swift还没有实现(xCode6 beta)通过mac+left click点进去后,里面啥也没有。到是在stackoverflow上看到有大神使用的,没有尝试:

    NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
    [inv setTarget: self];
    [inv setSelector:@selector(onTick:)];
    
    NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                          invocation:inv 
                          repeats:YES];
    

    显然在swift中,还没有NSInvocation.invocationWithMethodSignature方法的实现。

    第二个构造函数,通过它可以实例化NSTimer对象,但只能触发一次。之后就没用了,貌似repeats的参数是没有作用的。

    var timer = NSTimer(1.0, target: self, selector: "timerFireMethod:", userInfo: nil, repeats:true);
    timer.fire()
    

    后来看到网上大家都使用的静态函数的形式实例化,也尝试了一下,竟然成功了:

        func doTimer(){
            var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerFireMethod:", userInfo: nil, repeats:true);
            timer.fire()
        }
        func timerFireMethod(timer: NSTimer) {
            var formatter = NSDateFormatter();
            formatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
            var strNow = formatter.stringFromDate(NSDate())
            txta.text  = "(strNow)"
        }
    

    程序的目的就是在view上的label中实时显示当前的时间。

    总结:

    1、NSTimer只能使用静态函数来实例化该对象

    2、使用静态函数来实例化对象的时候,竟然需要传一个实例对象的方法(通过selector),这个感觉有些违背面向对象的思想的。任何对象的成员的访问都需要通过实例化对象来调用。swift中有全局函数,想想也释然了,毕竟他是一门刚出来的语言还是需要时间沉淀的。

    3、在模拟器中,运行10分钟,程序所使用的memory,从12.0MB上升到了12.5MB。感觉对内存的要求还是比较高的,不知道有没有其它更好的方法实现。

  • 相关阅读:
    二叉排序树的建立_查找_插入_删除
    java学习书籍推荐
    Java之路——敬JAVA初学者(作者:MoMo)
    结构体的定义及应用
    java获取缓存通用类
    金额转换为自定义字符串
    WebApi接入Swagger
    webApi的控制台服务
    自动生成缓存Key值的CacheKeyHelper
    DictionaryHelper2
  • 原文地址:https://www.cnblogs.com/sxlfybb/p/3792611.html
Copyright © 2020-2023  润新知