2011-11-21 109 views
0

第一個問題,我已經研究了這一點,似乎無法找到任何答案。如何在達到0時重置倒數計時器? (Xcode 4)

我想在我的應用程序中實現一個倒數計時器,該計時器在30秒開始,並在打到0時重置。它將以1秒爲間隔計數。我玩過蘋果提供的資源,我似乎無法按照我剛剛解釋的那樣實施NStimer。有沒有關於我如何編碼的建議?我最終希望將其鏈接到一個按鈕,該按鈕將在按下時啓動計時器。我很欣賞這個話題的任何建議!

回答

1

在您的.h

@interface YourObject : NSObject { 
    int countdownNumber; 
    NSTimer* timer; 
} 

@property (nonatomic, assign) int countdownNumber; 
@property (nonatomic, retain) NSTimer* timer; 

- (IBAction)clickOnButton:(id)sender 
- (void)countdown; 
@end 

在您的m

yourInitMethod { // ViewDidLoad, initWith...., or any init method you have 
    self.timer = nil; 
} 

- (IBAction)clickOnButton:(id)sender { 
    if (self.timer != nil) { 
     [self.timer invalidate]; 
    } 

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

- (void)countdown { 
    self.countdownNumber--; 
    if (self.countdownNumber == 0) { 
     [self.timer invalidate]; 
     self.timer = nil; 
    } 
}