你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發基礎 >> NSTimer你真的會用了嗎

NSTimer你真的會用了嗎

編輯:IOS開發基礎

到這個標題,你可能會想NSTimer不就是計時器嗎,誰不會用,不就是一個能夠定時的完成任務的東西嗎?

我想說你知道NSTimer會retain你添加調用方法的對象嗎?你知道NSTimer是要加到runloop中才會起作用嗎?你知道NSTimer會並不是准確的按照你指定的時間觸發的嗎?你知道NSTimer就算添加到runloop了也不一定會按照你想象中的那樣執行嗎?

如果上面提出的哪些問題,你並不全部了解,那麼請細心的看完下面的文章,上面的那幾個問題我會一一說明,並給出詳細的例子。

一、什麼是NSTimer

官方給出解釋是“A timer provides a way to perform a delayed action or a periodic action. The timer waits until a certain time interval has elapsed and then fires, sending a specified message to a specified object. ” 翻譯過來就是timer就是一個能在從現在開始的後面的某一個時刻或者周期性的執行我們指定的方法的對象。

二、NSTimer和它調用的函數對象間到底發生了什麼

從前面官方給出的解釋可以看出timer會在未來的某個時刻執行一次或者多次我們指定的方法,這也就牽扯出一個問題,如何保證timer在未來的某個時刻觸發指定事件的時候,我們指定的方法是有效的呢?

解決方法很簡單,只要將指定給timer的方法的接收者retain一份就搞定了,實際上系統也是這樣做的。不管是重復性的timer還是一次性的timer都會對它的方法的接收者進行retain,這兩種timer的區別在於“一次性的timer在完成調用以後會自動將自己invalidate,而重復的timer則將永生,直到你顯示的invalidate它為止”。

下面我們看個小例子:

SvTestObject.m

//
//  SvTestObject.m
//  SvTimerSample
//
//  Created by  maple on 12/19/12.
//  Copyright (c) 2012 maple. All rights reserved.
//
#import "SvTestObject.h"
@implementation SvTestObject
- (id)init
{
    self = [super init];   
     if (self) {
     
        NSLog(@"instance %@ has been created!", self);
        
    }    
    
    return self;
}
- (void)dealloc
{
    NSLog(@"instance %@ has been dealloced!", self);
    
    [super dealloc];
}
- (void)timerAction:(NSTimer*)timer
{
   
    NSLog(@"Hi, Timer Action for instance %@", self);
    
}

@end

SvTestObject.h

//
//  SvTestObject.h
//  SvTimerSample
//
//  Created by  maple on 12/19/12.
//  Copyright (c) 2012 maple. All rights reserved.
//
#import @interface SvTestObject : NSObject
/*
 * @brief timer響應函數,只是用來做測試
 */
- (void)timerAction:(NSTimer*)timer;

@end
SvTimerAppDelegate.m
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    // test Timer retain target
    [self testNonRepeatTimer];
//    [self testRepeatTimer];
}
- (void)testNonRepeatTimer
{
    NSLog(@"Test retatin target for non-repeat timer!");
    SvTestObject *testObject = [[SvTestObject alloc] init];
    [NSTimer scheduledTimerWithTimeInterval:5 target:testObject selector:@selector(timerAction:) userInfo:nil repeats:NO];
    [testObject release];
    NSLog(@"Invoke release to testObject!");
}
- (void)testRepeatTimer
{
    NSLog(@"Test retain target for repeat Timer");
    SvTestObject *testObject2 = [[SvTestObject alloc] init];
    [NSTimer scheduledTimerWithTimeInterval:5 target:testObject2 selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [testObject2 release];
    NSLog(@"Invoke release to testObject2!");
}

上面的簡單例子中,我們自定義了一個繼承自NSObject的類SvTestObject,在這個類的init,dealloc和它的timerAction三個方法中分別打印信息。然後在appDelegate中分別測試一個單次執行的timer和一個重復執行的timer對方法接受者是否做了retain操作,因此我們在兩種情況下都是shedule完timer之後立馬對該測試對象執行release操作。

測試單次執行的timer的結果如下:

1.png

觀察輸出,我們會發現53分58秒的時候我們就對測試對象執行了release操作,但是知道54分03秒的時候timer觸發完方法以後,該對象才實際的執行了dealloc方法。這就證明一次性的timer也會retain它的方法接收者,直到自己失效為之。

測試重復性的timer的結果如下:

2.png

觀察輸出我們發現,這個重復性的timer一直都在周期性的調用我們為它指定的方法,而且測試的對象也一直沒有真正的被釋放。

通過以上小例子,我們可以發現在timer對它的接收者進行retain,從而保證了timer調用時的正確性,但是又引入了接收者的內存管理問題。特別是對於重復性的timer,它所引用的對象將一直存在,將會造成內存洩露。

有問題就有應對方法,NSTimer提供了一個方法invalidate,讓我們可以解決這種問題。不管是一次性的還是重復性的timer,在執行完invalidate以後都會變成無效,因此對於重復性的timer我們一定要有對應的invalidate。

突然想起一種自欺欺人的寫法,不知道你們有沒有這麼寫過,我承認之前也有這樣寫過,哈哈,代碼如下:

SvCheatYourself.m

//
//  SvCheatYourself.m
//  SvTimerSample
//
//  Created by  maple on 12/19/12.
//  Copyright (c) 2012 maple. All rights reserved.
//
//  以下這種timer的用法,企圖在dealloc中對timer進行invalidate是一種自欺欺人的做法
//  因為你的timer對self進行了retain,如果timer一直有效,則self的引用計數永遠不會等於0
#import "SvCheatYourself.h"
@interface SvCheatYourself () {

    NSTimer *_timer;
    
}
@end
@implementation SvCheatYourself

- (id)init
{
    self = [super init];
    if (self) {
    
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(testTimer:) userInfo:nil repeats:YES];
        
    }
    
    return self;
}
- (void)dealloc
{
    // 自欺欺人的寫法,永遠都不會執行到,除非你在外部手動invalidate這個timer
    [_timer invalidate];
    
    [super dealloc];
}
- (void)testTimer:(NSTimer*)timer
{
    NSLog(@"haha!");
}
@end

綜上: timer都會對它的target進行retain,我們需要小心對待這個target的生命周期問題,尤其是重復性的timer。

三、NSTimer會是准時觸發事件嗎

答案是否定的,而且有時候你會發現實際的觸發時間跟你想象的差距還比較大。NSTimer不是一個實時系統,因此不管是一次性的還是周期性的timer的實際觸發事件的時間可能都會跟我們預想的會有出入。差距的大小跟當前我們程序的執行情況有關系,比如可能程序是多線程的,而你的timer只是添加在某一個線程的runloop的某一種指定的runloopmode中,由於多線程通常都是分時執行的,而且每次執行的mode也可能隨著實際情況發生變化。

假設你添加了一個timer指定2秒後觸發某一個事件,但是簽好那個時候當前線程在執行一個連續運算(例如大數據塊的處理等),這個時候timer就會延遲到該連續運算執行完以後才會執行。重復性的timer遇到這種情況,如果延遲超過了一個周期,則會和後面的觸發進行合並,即在一個周期內只會觸發一次。但是不管該timer的觸發時間延遲的有多離譜,他後面的timer的觸發時間總是倍數於第一次添加timer的間隙。

原文如下“A repeating timer reschedules itself based on the scheduled firing time, not the actual firing time. For example, if a timer is scheduled to fire at a particular time and every 5 seconds after that, the scheduled firing time will always fall on the original 5 second time intervals, even if the actual firing time gets delayed. If the firing time is delayed so far that it passes one or more of the scheduled firing times, the timer is fired only once for that time period; the timer is then rescheduled, after firing, for the next scheduled firing time in the future.”

下面請看一個簡單的例子:

Simulate Thread Busy

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    SvTestObject *testObject2 = [[SvTestObject alloc] init];
    [NSTimer scheduledTimerWithTimeInterval:1 target:testObject2 selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [testObject2 release];
    
    NSLog(@"Simulate busy");
    [self performSelector:@selector(simulateBusy) withObject:nil afterDelay:3];
}

// 模擬當前線程正好繁忙的情況
- (void)simulateBusy
{
    NSLog(@"start simulate busy!");
    
    NSUInteger caculateCount = 0x0FFFFFFF;
    
    CGFloat uselessValue = 0;
    
    for (NSUInteger i = 0; i < caculateCount; ++i) {
    
        uselessValue = i / 0.3333;
        
    }
    
    NSLog(@"finish simulate busy!");
}

例子中首先開啟了一個timer,這個timer每隔1秒調用一次target的timerAction方法,緊接著我們在3秒後調用了一個模擬線程繁忙的方法(其實就是一個大的循環)。運行程序後輸出結果如下:

3.png

觀察結果我們可以發現,當線程空閒的時候timer的消息觸發還是比較准確的,但是在36分12秒開始線程一直忙著做大量運算,知道36分14秒該運算才結束,這個時候timer才觸發消息,這個線程繁忙的過程超過了一個周期,但是timer並沒有連著觸發兩次消息,而只是觸發了一次。等線程忙完以後後面的消息觸發的時間仍然都是整數倍與開始我們指定的時間,這也從側面證明,timer並不會因為觸發延遲而導致後面的觸發時間發生延遲。

綜上: timer不是一種實時的機制,會存在延遲,而且延遲的程度跟當前線程的執行情況有關。

四、NSTimer為什麼要添加到RunLoop中才會有作用

前面的例子中我們使用的是一種便利方法,它其實是做了兩件事:首先創建一個timer,然後將該timer添加到當前runloop的default mode中。也就是這個便利方法給我們造成了只要創建了timer就可以生效的錯覺,我們當然可以自己創建timer,然後手動的把它添加到指定runloop的指定mode中去。

NSTimer其實也是一種資源,如果看過多線程變成指引文檔的話,我們會發現所有的source如果要起作用,就得加到runloop中去。同理timer這種資源要想起作用,那肯定也需要加到runloop中才會又效喽。如果一個runloop裡面不包含任何資源的話,運行該runloop時會立馬退出。你可能會說那我們APP的主線程的runloop我們沒有往其中添加任何資源,為什麼它還好好的運行。我們不添加,不代表框架沒有添加,如果有興趣的話你可以打印一下main thread的runloop,你會發現有很多資源。 

下面我們看一個小例子:  

- (void)applicationDidBecomeActive:(UIApplication *)application
{

    [self testTimerWithOutShedule];
    
}
- (void)testTimerWithOutShedule
{

    NSLog(@"Test timer without shedult to runloop");
    
    SvTestObject *testObject3 = [[SvTestObject alloc] init];
    
    NSTimer *timer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:1] interval:1 target:testObject3 selector:@selector(timerAction:) userInfo:nil repeats:NO];
    
    [testObject3 release];
    
    NSLog(@"invoke release to testObject3");
    
}
- (void)applicationWillResignActive:(UIApplication *)application
{

    NSLog(@"SvTimerSample Will resign Avtive!");
    
}

這個小例子中我們新建了一個timer,為它指定了有效的target和selector,並指出了1秒後觸發該消息,運行結果如下:

4.png

觀察發現這個消息永遠也不會觸發,原因很簡單,我們沒有將timer添加到runloop中。

綜上: 必須得把timer添加到runloop中,它才會生效。

五、NSTimer加到了RunLoop中但遲遲的不觸發事件

為什麼明明添加了,但是就是不按照預先的邏輯觸發事件呢???原因主要有以下兩個:

1、runloop是否運行

每一個線程都有它自己的runloop,程序的主線程會自動的使runloop生效,但對於我們自己新建的線程,它的runloop是不會自己運行起來,當我們需要使用它的runloop時,就得自己啟動。

那麼如果我們把一個timer添加到了非主線的runloop中,它還會按照預期按時觸發嗎?下面請看一段測試程序:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [NSThread detachNewThreadSelector:@selector(testTimerSheduleToRunloop1) toTarget:self withObject:nil];
}
// 測試把timer加到不運行的runloop上的情況
- (void)testTimerSheduleToRunloop1
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSLog(@"Test timer shedult to a non-running runloop");
    
    SvTestObject *testObject4 = [[SvTestObject alloc] init];
    
    NSTimer *timer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:1] interval:1 target:testObject4 selector:@selector(timerAction:) userInfo:nil repeats:NO];
    
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    // 打開下面一行輸出runloop的內容就可以看出,timer卻是已經被添加進去
    //NSLog(@"the thread's runloop: %@", [NSRunLoop currentRunLoop]);
    
    // 打開下面一行, 該線程的runloop就會運行起來,timer才會起作用
    //[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
    
    [testObject4 release];
    
    NSLog(@"invoke release to testObject4");
    [pool release];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    NSLog(@"SvTimerSample Will resign Avtive!");
}

上面的程序中,我們新創建了一個線程,然後創建一個timer,並把它添加當該線程的runloop當中,但是運行結果如下:

5.png

觀察運行結果,我們發現這個timer知道執行退出也沒有觸發我們指定的方法,如果我們把上面測試程序中“//[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];”這一行的注釋去掉,則timer將會正確的掉用我們指定的方法。

2、mode是否正確

我們前面自己動手添加runloop的時候,可以看到有一個參數runloopMode,這個參數是干嘛的呢?

前面提到了要想timer生效,我們就得把它添加到指定runloop的指定mode中去,通常是主線程的defalut mode。但有時我們這樣做了,卻仍然發現timer還是沒有觸發事件。這是為什麼呢?

這是因為timer添加的時候,我們需要指定一個mode,因為同一線程的runloop在運行的時候,任意時刻只能處於一種mode。所以只能當程序處於這種mode的時候,timer才能得到觸發事件的機會。

舉個不恰當的例子,我們說兄弟幾個分別代表runloop的mode,timer代表他們自己的才水桶,然後一群人去排隊打水,只有一個水龍頭,那麼同一時刻,肯定只能有一個人處於接水的狀態。也就是說你雖然給了老二一個桶,但是還沒輪到它,那麼你就得等,只有輪到他的時候你的水桶才能碰上用場。

綜上: 要讓timer生效,必須保證該線程的runloop已啟動,而且其運行的runloopmode也要匹配。


  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved