swift 定时器的使用

在swift中,要使用定时器就须要用到对象NSTimer。经过NSTimer的实例化后,就能够调用fire方法来启用了。swift

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上看到有大神使用的,没有尝试:orm

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的参数是没有做用的。blog

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中实时显示当前的时间。get

 

总结:string

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

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

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

相关文章
相关标签/搜索