iOS Label Text Based On Timed Function
Question
I've been trying to create a script that sets a timer and reduces a value by 33 each time it runs. In theory the timer should stop itself after 6 runs, but it keeps going and reaches negative values. Is there a reason for this?
-(void)checkValue:(NSTimer *)myTimer{
if(pplint > 0){
pplint = pplint-33;
NSString *ppllefttext = [NSString stringWithFormat:@"%d", pplint];
peopleleft.text = ppllefttext;
NSLog(@"Reduced Timer");
}
if(pplint < 0){
NSLog(@"Stop Timer");
[myTimer invalidate];
}
}
- (IBAction)gotocongrats{
pplint = 198;
NSString *ppllefttext = [NSString stringWithFormat:@"%d", pplint];
peopleleft.text = ppllefttext;
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(checkValue:)
userInfo:nil
repeats:YES];
NSLog(@"Started Timer");
}
Solution
I took you code and edited it a bit and it works just fine for me.
-(void)checkValue:(NSTimer *)myTimer{
if(pplint > 0){
pplint = pplint-33;
NSLog(@"%i",pplint);
NSLog(@"Reduced Timer");
}
if(pplint <= 0){
NSLog(@"Stop Timer");
[myTimer invalidate];
}
}
- (IBAction)gotocongrats{
pplint = 198;
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(checkValue:)
userInfo:nil
repeats:YES];
NSLog(@"Started Timer");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow