2012-05-04 258 views
0

以下方法导致崩溃。用户界面就像一个按钮,它处理NSTimer的开始/停止功能。如果定时器运行,则更新UILabel。使用viewDidLoad方法使我的计时器工作,停止工作,但再次启动会崩溃应用程序。NSTimer导致崩溃

删除viewDidLoad方法中的alloc并尝试使用开始按钮导致崩溃立即。即使NSLog(@"Start now");未被调用。

代码:

- (void)tick { 
NSLog(@"tick"); 
float value = [moneyLabel.text floatValue]; 
moneyLabel.text = [NSString stringWithFormat:@"%f", value + 1.0]; 

} 

- (IBAction)startStopButtonClicked:(UIButton *)sender { 
if ([sender.titleLabel.text isEqualToString:@"Start"]) { 
    NSLog(@"Start now"); 
    if (timer) { 
     NSLog(@"Timer valid"); 
     [timer fire]; 
    } else { 
     NSLog(@"Timer is nil"); 
     timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tick) userInfo:nil repeats:YES]; 
     [timer fire]; 
    } 

    NSLog(@"bla"); 

    [sender setTitle:@"Stop" forState:UIControlStateNormal]; 
} else { 
    [timer invalidate]; 
    timer = nil; 
    NSLog(@"Stopped."); 
    NSLog(@"Timer isValid: %@", timer); 
    [sender setTitle:@"Start" forState:UIControlStateNormal]; 
} 
} 
+1

发布您的崩溃日志。 – Devang

+0

是PLZ发表您的崩溃日志,以便我们可以帮助你... – sandy

+0

***终止应用程序由于未捕获的异常“NSInvalidArgumentException”,原因是:“ - [__ NSCFArray startStopButtonClicked:]:无法识别的选择发送到实例0x683d8e0” – DAS

回答

0

你的代码已经发布的作品 - 只是测试它在一个新项目中,所以问题可能在其他地方。我只通过在viewDidLoad:或指定的初始化程序中声明而没有任何初始化来测试它。

+1

问题是在AppDelegate中没有添加rootViewController。 WTF。 – DAS

3

我不认为需要调用[NSTimer fire]可言;它应该足以让计时器决定何时开火。

首先确保timernil(它应该是,如果它的对象的实例变量),虽然明确地将它设置为nil- (id)init不会受到伤害。

接下来我会使用定时器本身的状态,以确定启动/停止是否被按下,而不是在按钮上的文字:根据需要

- (IBAction)startStopButtonClicked:(UIButton *)sender 
{ 
    if (timer != nil) 
    { 
     NSLog(@"Stopping timer"); 
     [timer invalidate]; 
     timer = nil; 
    } 
    else 
    { 
     NSLog(@"Starting timer"); 
     timer = [NSTimer scheduledTimerWithTimeInterval:1 
               target:self 
               selector:@selector(tick) 
               userInfo:nil 
               repeats:YES]; 
    } 

    [sender setTitle:(timer != nil ? @"Stop" : @"Start") 
      forState:UIControlStateNormal]; 
} 
+0

** *终止应用程序,由于未捕获异常'NSInvalidArgumentException',原因:' - [__ NSCFArray startStopButtonClicked:]:无法识别的选择器发送到实例0x683d8e0' – DAS

+0

@达尔文这看起来像是你已发布的代码之外的崩溃。鉴于另一个答案似乎表明这个代码的作品,它看起来像你在错误的地方看。 – trojanfoe

+0

除此之外,我的项目中没有任何代码......其他所有内容都是像viewDidLoad一样的标准。多么糟糕...... – DAS