2011-04-24 97 views

回答

1

你需要使用NSTimer

檢查下面的代碼作爲參考。

- (void) startCounter { 
    counterCount = 0; 
    [NSTimer scheduledTimerWithInterval:0.09f target:self selector:@selector(showElapsedTime:) userInfo:nil repeats:YES]; 
} 

showElapsedTime將在延遲後調用,您提供。

-(void) showElapsedTime: (NSTimer *) timer { 
    counterCount++; 
    if(counterCount == 10) 
    { 
     [timer invalidate]; 
    } 

// Write your code here 
} 
+0

你只需要在某些時候使計時器無效,而上面的代碼沒有說明。編輯:上面的代碼現在可以工作,但靜態計數器在這種情況下比伊娃更有意義。 – Christian 2011-04-24 19:03:26

+0

@Christian:是的,你是對的,已經更新了答案... – Jhaliya 2011-04-24 19:05:13

+0

太棒了!謝謝,這正是我需要的! :) – Oscar 2011-04-25 10:59:34

1

創建一個NSTimer:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds 
            target:(id)target 
            selector:(SEL)aSelector 
            userInfo:(id)userInfo 
            repeats:(BOOL)repeats; 

此致可能會是這樣的:

[NSTimer scheduledTimerWithTimeInterval:1.0 
            target:self 
           selector:@selector(timerFired:) 
           userInfo:nil 
           repeats:YES]; 

在被調用的方法,增加一個計數器,並檢查是否達到了您的計數停止定時器:

- (void)timerFired:(NSTimer *)timer 
{ 
    static int counter = 0; 

    // Do Something 

    counter++; 
    if(counter == 10) 
      [timer invalidate]; 
} 
0

NSObject類的方法[performSelector: withObject: afterDelay]通常用於定時操作。