objective-c - NSTimer问题

标签 objective-c iphone xcode

所以我正在尝试设置一个基本计时器,但失败得很惨。基本上我想要的只是在用户单击按钮时启动 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

关于objective-c - NSTimer问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3220695/

相关文章:

iphone - 直到 pushViewController 才应用外观更改

ios - iOS 中 View 的人类可读标签/ID

ios - 使用 Xcode 出现错误 "No such module",但框架存在

ios - 在 const NSString *const[] 中查找 NSString

ios - iOS 上 Objective-C 中的类型

iphone - iOS5中如何获取联系人访问权限?

iphone nsurlconnection 读取cookie

ios - 自定义标记性能 iOS,崩溃,结果为 "((null)) was false: Reached the max number of texture atlases, can not allocate more."

iphone - 在方法中运行时,从 nib 加载的 View 不会更新 UILabel 的内容

ios - Parse.com 关系对象指定顺序