2011-11-30 245 views
0

使用NSTimer爲我的應用程序,我必須顯示倒數計時器初始時間等於100秒。它顯示99,然後顯示98..96..94..92 ... 86等等。但我希望每一秒都出現。這裏是我的代碼....無法獲得NSTimer工作

-(void)updateTimerLabel{ 
    if (timeRemaining>0) { 



    timeRemaining=timeRemaining-1.0; 
    timerLabel.text=[NSString stringWithFormat:@"%.0f", timeRemaining]; 


    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES]; 
    } 
} 
+1

在您的選擇器方法外寫入計時器方法 – Narayana

回答

1

嘗試以下代碼

int i =100; 

-(void)viewDidLoad 
{ 
[super viewDidLoad]; 
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(theActionMethod) userInfo:nil repeats:YES]; 

} 

-(void)theActionMethod 
{ 
    if(i > 0) 
    { 
     NSString *str = [NSString stringWithFormat:@"%d",i]; 
     lbl.text = str; 
    } 
    i--; 
} 
1

您實際上是每次調用方法時重新創建計時器。

你應該嘗試離開那個外面並保留它,直到你完成它。

@interface SomeClass 

NSTimer * aTimer; 

@end 

@implementation 

- (void)createTimer { 
    aTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES] retain]; 
} 

- (void)updateTimerLabel { 
    // do timer updates here 

    // call [aTimer release] 
    // and [aTimer invalidate] 
    // aTimer = nil; 
    // when you're done 
} 

@end 
0

您已在方法外調用updateTimerLabel。 例如: - (無效)viewDidLoad中{timeRemaining = 100.0; [自updateTimerLabel]; countdownTimer = [的NSTimer scheduledTimerWithTimeInterval:1.0目標:自選擇器:@selector(updateTimerLabel)USERINFO:無重複:YES];}

- (空隙)updateTimerLabel {如果(timeRemaining> 0) {timeRemaining = timeRemaining-1.0;的NSLog(@ 「%@」,[的NSString stringWithFormat: 「%0F」 @,timeRemaining]);}}