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。感覺對內存的要求還是比較高的,不知道有沒有其它更好的方法實現。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM