2013-03-14 15 views
3

我想讓每兩秒鐘出現10次不同的東西。我如何在Objective-C中實現這一點?如果我想每隔x秒執行一次方法y次,我應該使用NSTimer嗎?

我正在考慮使用NSTimer並在如此多秒之後使其無效,就像我在啓動計時器後的上述示例2 * 10秒一樣。或者有沒有辦法測量滴答?

或者我正在考慮for循環並使用performSelector:withDelay:方法。

哪個更好?

+0

使用重複計時器。還有一個類屬性,它是一個整數,用於跟蹤您的計時器被調用的次數。 – Rob 2013-03-14 18:16:42

回答

7

使用NSTimer並將時間interval設置爲2 secondsrepeatsYES

計算它觸發的次數。 Invalidate,當它到達10.Thats它

代碼:

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(trigger:) userInfo:yourObject repeats:YES]; 

- (void)trigger:(NSTimer *)sender{ 

    id yourObject = sender.userInfo; 

    static int count = 1; 

    @try { 

     NSLog(@"triggred %d time",count); 

     if (count == 10){ 

      [sender invalidate]; 
      NSLog(@"invalidated"); 
     } 

    } 
    @catch (NSException *exception) 
    { 
     NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]); 
    } 
    @finally { 

     count ++; 
    } 
} 
+0

我計算在我調用的方法內觸發的次數嗎?當它達到此限制時,我該如何使其無效? – 2013-03-14 19:11:02

+0

我已經添加了方法...請檢查它' – 2013-03-14 19:45:50

+0

如果我想10可能根據使用情況更改爲不同的數字,該怎麼辦?我可以使用該方法的參數嗎? – 2013-03-14 21:45:12

3

我用你的第二個選項,沒有定時器需要

for (int a=0; a<10; a++) { 
    [self performSelector:@selector(print) withObject:nil afterDelay:2.0*a]; 
} 


-(void)print 
{ 
    NSLog(@"sth"); 
} 

你可以做的時間間隔和重複計數靈活。

相關問題