I am writing a iPhone app that times how long the user is holding onto the bu开发者_开发技巧tton. When the user 'Touches Down' the buttonPressed method is fired and when the button is realeased aka no longer being held the NSTimer is supposed to invalidate. However, it is not and I am having a extremely difficult time finding a solution. Hope you guys can help! Here's the code:
-(IBAction)buttonReleased:(id)sender {
[stopWatchTimer invalidate];
NSString *label0 = @"0";
[labelText setText:label0];
score--;
NSString *scoreMessage =[[NSString alloc] initWithFormat:@"YOU LOSE! Your score was: %i",score];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"GAME OVER!" message:(NSString *)scoreMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
score = 0;
tap = 0;
}
- (void)updateTimer
{
static NSInteger counter = 0;
labelText.text = [NSString stringWithFormat:@"%d", counter++];
score++;
}
-(IBAction)buttonPressed:(id)sender {
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/1.0 target:self selector:@selector(updateTimer)userInfo:nil repeats:YES];
tap++;
}
What actually calls buttonReleased:
? There are several ways that a button can stop being held down. The touch up might be inside or outside of the button for instance.
My strong suspicion is that buttonPressed:
is called more often than buttonReleased:
. Because you're directly accessing your ivars rather than using accessors, you're not handling this correctly, and you're probably leaving around old timers when you assign a new timer.
First, always use accessors. Don't mess with ivars directly (the exceptions are in init
, dealloc
and in accessors themselves). Many problems like this one come from messing with ivars directly. (Plus, it makes the code confusing. Is score
a local, global or ivar?)
Second, an NSTimer
setter should look like this:
- (void)setTimer:(NSTimer *)aTimer {
if (aTimer != timer_) {
[timer_ invalidate];
[timer_ release];
timer_ = [aTimer retain];
}
}
This ensures that when you replace a timer, you invalidate the old one. The if()
check is important on the off-chance that you call the equivalent of self.timer = self.timer
. If you did that without an if()
check you would invalidate the timer when you didn't mean to.
精彩评论