2013-11-15 80 views
6

我正在開發一個應用程序,我想在使用dispatch_async的單獨隊列中調用方法。我想在一定的時間間隔後重復調用該方法。但該方法沒有被調用。未用dispatch_async調用方法並重復NSTimer

我不知道什麼是錯的。這裏是我的代碼:

dispatch_async(NotificationQueue, ^{ 

     NSLog(@"inside queue"); 
     timer = [NSTimer scheduledTimerWithTimeInterval: 20.0 
               target: self 
               selector: @selector(gettingNotification) 
               userInfo: nil 
               repeats: YES]; 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      // Add code here to update the UI/send notifications based on the 
      // results of the background processing 

     }); 
    }); 

-(void)gettingNotification { 
    NSLog(@"calling method "); 
} 

回答

9

如果你想有一個重複的計時器上一個dispatch_queue_t被調用,使用dispatch_source_createDISPATCH_SOURCE_TYPE_TIMER

dispatch_queue_t queue = dispatch_queue_create("com.firm.app.timer", 0); 
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); 
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 20ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC); 

dispatch_source_set_event_handler(timer, ^{ 

    // stuff performed on background queue goes here 

    NSLog(@"done on custom background queue"); 

    // if you need to also do any UI updates, synchronize model updates, 
    // or the like, dispatch that back to the main queue: 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSLog(@"done on main queue"); 
    }); 
}); 

dispatch_resume(timer); 

這造成運行一次每20秒的計時器(第三參數dispatch_source_set_timer),用一秒的(第四參數dispatch_source_set_timer)一個餘地。

要取消此計時器,使用dispatch_source_cancel

dispatch_source_cancel(timer); 
+0

只需將上述內容添加到視圖中,在vc中加載不會生成任何控制檯輸出,缺少什麼? –

+1

@DavidKarlsson'timer'變量實際上必須是類屬性(或ivar)。與'NSTiner'不同,如果超出範圍,則調度計時器將被取消並解除分配。 – Rob

1

試試這個代碼

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

    dispatch_async(dispatch_get_main_queue(), ^{ 

     timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self 
               selector: @selector(gettingNotification) userInfo: nil repeats: YES]; 
     // Add code here to update the UI/send notifications based on the 
     // results of the background processing 

    }); 
}); 

-(void)gettingNotification { 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     //background task here 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // update UI here 
     ); 
}); 
} 
+1

這也是正確的,但派遣源可能是更直接的機制。不過,這個答案可以簡化,因爲將定時器的創建分派給後臺隊列,然後再分配給主隊列是沒有意義的。只需在主隊列中創建重複計時器,而不需要兩次嵌套調度。仍然是+1。 – Rob