2013-08-13 14 views
5

私はタイマーを使用するゲームを持っています。ユーザーがボタンを選択してそのタイマーを一時停止させ、そのボタンを再びクリックすると、そのタイマーのポーズを解除します。私はすでにタイマーのコードを持っています。タイマーとデュアルアクションボタンを一時停止するだけの助けが必要です。タイマーへNSTimerを一時停止するには?

コード:

-(void)timerDelay { 

    mainInt = 36; 

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
             target:self 
             selector:@selector(countDownDuration) 
             userInfo:nil 
             repeats:YES]; 
} 

-(void)countDownDuration { 

    MainInt -= 1; 

    seconds.text = [NSString stringWithFormat:@"%i", MainInt]; 
    if (MainInt <= 0) { 
     [timer invalidate]; 
     [self delay]; 
    } 

} 
+0

TBlueの回答を正しいとマークしても問題が解決しない場合は、正しいとマークしてください。そのコードを質問に編集するか、タイトルに[解決済み]を追加する必要はありません。 StackOverflowでの適切な投稿方法の詳細については、[ヘルプ]を読むことをお勧めします。 – madth3

答えて

16

これは非常に簡単です。

// Declare the following variables 
BOOL ispaused; 
NSTimer *timer; 
int MainInt; 

-(void)countUp { 
    if (ispaused == NO) { 
     MainInt +=1; 
     secondField.stringValue = [NSString stringWithFormat:@"%i",MainInt]; 
    } 
} 

- (IBAction)start1Clicked:(id)sender { 
    MainInt=0; 
    timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUp) userInfo:Nil repeats:YES]; 
} 

- (IBAction)pause1Clicked:(id)sender { 
    ispaused = YES; 
} 

- (IBAction)resume1Clicked:(id)sender { 
    ispaused = NO; 
} 
5

NSTimerには一時停止と再開機能はありません。あなたは以下のコードのようにそれを含めることができます。

- (void)startTimer 
{ 
    m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES]; 
} 

- (void)fireTimer:(NSTimer *)inTimer 
{ 
    // Timer is fired. 
} 

- (void)resumeTimer 
{ 
    if(m_pTimerObject) 
    { 
     [m_pTimerObject invalidate]; 
     m_pTimerObject = nil;   
    } 
    m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES]; 
} 

- (void)pauseTimer 
{ 
    [m_pTimerObject invalidate]; 
    m_pTimerObject = nil; 
} 
+5

これは一時停止せず、停止して再起動します。 –

+0

@CarlVeazey答えに言及すると、「NSTimer」には「ポーズ」機能がないため、(受け入れられたものを含む)すべての回答は、その事実を回避する必要があります。何もしていないタイマーは稼動していないので、この回答は受け入れられたものより優れています。 +1 –

+0

@Nate重複の回答は、この事実を回避するにはまだポーズ機能を提供しているようです。私はそれを指摘することが不合理だとは思わない。 –

関連する問題