objective-c – NSTimer问题

前端之家收集整理的这篇文章主要介绍了objective-c – NSTimer问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我试图建立一个基本的计时器,但我失败了.基本上我想要的是在用户点击按钮时启动60秒计时器,并用剩余时间更新标签(如倒计时).我创建了我的标签和按钮并将它们连接到IB中.接下来,我为按钮创建了一个IBAction.现在,当我尝试根据计时器更新标签时,我的应用程序搞砸了.这是我的代码

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

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

解决方法

好的,对于初学者来说,如果你还没有,请检查一下: Official Apple Docs about Using Timers

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

此示例假定您要保留对计时器的引用,以便您可以暂停它或其他内容.如果不是这种情况,您可以修改handleTimerTick方法,以便将NSTimer *作为参数,并在计时器到期后使用它来使计时器失效.

@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

猜你在找的Xcode相关文章