为什么这个NSTimer会崩溃?

时间:2012-02-09 14:42:45

标签: objective-c nstimer

http://www.youtube.com/watch?v=5al6qqRzzQg当我点击一下不止一次??? 我需要做什么

#import "FirstViewController.h"

@implementation FirstViewController

-(IBAction)start;{

    myticker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
-(IBAction)stop;{ 

    [myticker invalidate];
}
-(IBAction)reset;{

    time.text = @"0";
}
-(void)showActivity;{ 

    int currentTime = [time.text intValue];
    int newTime = currentTime + 1;
    time.text = [NSString stringWithFormat:@"%d", newTime];
}


- (void)didReceiveMemoryWarning

2 个答案:

答案 0 :(得分:0)

将bool变量添加到类的标题中,如timerIsActive

-(IBAction)start;{
if (!timerIsActive) {
    myticker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
  timerIsActive = YES;

}
}

-(IBAction)stop;{ 
    timerIsActive = NO;
    [myticker invalidate];
}

答案 1 :(得分:0)

将启动和停止方法更改为:

-(IBAction)start;{

    [myticker invalidate];
    myticker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}

-(IBAction)stop;{ 

    [myticker invalidate];
    myticker = nil;
}

这将阻止它崩溃。另外,你应该添加:

-(void)dealloc
{
    [myticker invalidate];
}