【问题标题】:Trying to do a simple countdown application but counter isn't counting down?试图做一个简单的倒计时应用程序,但计数器没有倒计时?
【发布时间】:2015-02-05 03:31:39
【问题描述】:

我正在开发 Xcode 6 并尝试制作一个简单的倒计时应用程序。 我的应用程序真的很简单。 UI 有一个标签和一个按钮。当按钮被点击时,它应该从 10 开始倒计时。

这是我的代码:

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController

{
    NSInteger count;
    NSTimer *timer;
}

@property (weak, nonatomic) IBOutlet UILabel *timerLabel;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(IBAction)start {
    count = 10;
    timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
};

-(void)timerFired:(NSTimer *)timer {
    count -=1;
    self.timerLabel.text = [NSString stringWithFormat:@"%i",count];

    if (count == 0) {
        [timer invalidate];
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

程序编译得很好,但是当我单击按钮开始倒计时时没有任何反应。我哪里做错了?

编辑:非常感谢大家!问题解决了。我花了 3 个小时试图弄清楚我做错了什么,却发现这是一个愚蠢的错误。啊。 爱你stackoverflow!

【问题讨论】:

标签: ios objective-c iphone xcode nstimer


【解决方案1】:

您已正确设置触发方法,但计时器实际上并未触发。作为mentioned by Darren,您希望使用scheduledTimerWithTimeInterval 构造函数而不是timerWithTimeInterval 构造函数,除非您专门调用[NSTimer fire],否则它不会触发。

所以,只需为此切换旧的构造函数:

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

然后计时器应该正确触发(每秒)并调用相关的方法:

【讨论】:

    【解决方案2】:

    你应该使用这个 NStimer 初始方法。

    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
    

    代码中的主要问题是,

    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
    

    没有将你的计时器添加到runloop,所以你的计时器在一次调用后立即释放。并且scheduledTimerWithTimeInterval方法为你处理了runloop的事情。

    【讨论】:

      【解决方案3】:

      在你的代码中替换这一行

      timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
      

      用这条线

      timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
      

      【讨论】:

        猜你喜欢
        • 2012-08-16
        • 1970-01-01
        • 1970-01-01
        • 2016-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多