2012-09-08 48 views
-2

可能重複:
How to make a periodic call to a method in objective c?設置臨時定時器的iOS

我提出在當用戶觸摸屏幕的應用,下面的方法被稱爲:

- (void)explode:(int)x 

用戶只需觸摸一次屏幕,但我想要每隔0.1秒重複調用一次該方法100次,然後停止被叫。

有沒有一種方法可以在傳遞整數的方法上設置這樣的「臨時」計時器?

+6

是的,有幾種方法,如果您盡一切努力尋找它們,這些方法都會顯示給您。 –

回答

2

你可以傳遞一個計數器和'x'作爲定時器的userInfo。試試這個:

在正在迎頭趕上觸摸事件的方法創建定時器,並通過計數器和廉政「X」到用戶信息:

NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithCapacity:2]; 
[userInfo setValue:[NSNumber numberWithInt:x] forKey:@"x"]; 
[userInfo setValue:[NSNumber numberWithInt:0] forKey:@"counter"]; 

[NSTimer timerWithTimeInterval:0.1 
         target:self 
         selector:@selector(timerMethod:) 
         userInfo:userInfo 
         repeats:YES]; 

創建計時器方法,檢查用戶信息的數量計數,和100次後無效定時器:

- (void)timerMethod:(NSTimer *)timer 
{ 
    NSMutableDictionary *userInfo = timer.UserInfo; 
    int x = [[userInfo valueForKey:@"x"] intValue]; 

    // your code here 

    int counter = [[userInfo valueForKey:@"counter"] intValue]; 
    counter++; 

    if (counter >= 100) 
    { 
     [timer invalidate]; 
    } 
    else 
    { 
     [userInfo setValue:[NSNumber numberWithInt:x] forKey:@"x"]; 
     [userInfo setValue:[NSNumber numberWithInt:counter] forKey:@"counter"]; 
    } 

} 

也請參閱蘋果的文檔上NSTimer

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html

+0

如同我在問題中所說的那樣,將整數「x」傳遞給方法如何? –

+0

是的,你可以通過計時器的userInfo傳遞它,如果你願意的話。請參閱我上面編輯的答案。 –

+0

你很棒。謝謝 –