无法获得NSTimer工作
问题描述:
使用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];
}
}
答
尝试以下代码
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--;
}
答
您实际上是每次调用方法时重新创建计时器。
你应该尝试离开那个外面并保留它,直到你完成它。
@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
答
您已在方法外调用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]);}}
在您的选择器方法外写入计时器方法 – Narayana