NSTimer问题 [英] NSTimer problem

查看:77
本文介绍了NSTimer问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图建立一个基本的计时器,但我失败了。基本上我想要的是在用户点击按钮时启动60秒计时器,并用剩余时间更新标签(如倒计时)。我创建了我的标签和按钮并将它们连接到IB中。接下来,我为按钮创建了一个IBAction。现在,当我尝试根据计时器更新标签时,我的应用程序搞砸了。这是我的代码:

So I am trying to set up a basic timer but I am failing miserably. Basically all I want is to start a 60 second timer when the user clicks a button, and to update a label with the time remaining(like a countdown). I created my label and button and connected them in IB. Next I created a IBAction for the button. Now when I tried to update the label based on the timer, my app screws up. Here's my code:

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 1
                      target: self
                      selector:@selector(updateLabelDisplay)
                      userInfo: nil repeats:YES];

我还有一个updateLabelDisplay函数,用于确定计时器运行的次数,然后从中减去该次数。 60并在倒计时标签中显示该数字。谁能告诉我我做错了什么?

I also have an updateLabelDisplay function that determines how many times the timer has ran and then subtracted that number from 60 and displays that number in the countdown label. Can anyone tell me what I am doing wrong?

推荐答案

好的,对于初学者来说,如果你还没有,那就检查一下:有关使用计时器的官方Apple文档

Ok, well for starters, check this out if you haven't already: Official Apple Docs about Using Timers

根据您的描述,您可能希望代码看起来像这样。我已经对行为做了一些假设,但你可以适应品尝。

Based on your description, you probably want code that looks something like this. I've made some assumptions regarding behavior, but you can suit to taste.

这个例子假设你想要保留对计时器的引用,这样你就可以暂停它或什么。如果不是这种情况,您可以修改handleTimerTick方法,以便将NSTimer *作为参数,并在计时器到期后使用它来使计时器失效。

This example assumes that you want to hold on to a reference to the timer so that you could pause it or something. If this is not the case, you could modify the handleTimerTick method so that it takes an NSTimer* as an argument and use this for invalidating the timer once it has expired.

@interface MyController : UIViewController
{
  UILabel * theLabel;

  @private
  NSTimer * countdownTimer;
  NSUInteger remainingTicks;
}

@property (nonatomic, retain) IBOutlet UILabel * theLabel;

-(IBAction)doCountdown: (id)sender;

-(void)handleTimerTick;

-(void)updateLabel;

@end

@implementation MyController
@synthesize theLabel;

// { your own lifecycle code here.... }

-(IBAction)doCountdown: (id)sender
{
  if (countdownTimer)
    return;


  remainingTicks = 60;
  [self updateLabel];

  countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(handleTimerTick) userInfo: nil repeats: YES];
}

-(void)handleTimerTick
{
  remainingTicks--;
  [self updateLabel];

  if (remainingTicks <= 0) {
    [countdownTimer invalidate];
    countdownTimer = nil;
  }
}

-(void)updateLabel
{
  theLabel.text = [[NSNumber numberWithUnsignedInt: remainingTicks] stringValue];
}


@end

这篇关于NSTimer问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆