objective-c - 倒计时器

标签 objective-c cocoa

我正在尝试创建一个倒计时计时器,一个连接到文本字段的 IBOutlet,从 60 秒减少到 0。我不确定

一个。如何将重复次数限制在 60 次和

B.如何在 advanceTimer 中递减倒计时:

- (IBAction)startCountdown:(id)sender
{
    NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self     selector:@selector(advanceTimer:) userInfo:nil repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:countdownTimer forMode:NSDefaultRunLoopMode];
}

- (void)advanceTimer:(NSTimer *)timer
{
    [countdown setIntegerValue:59];
}

最佳答案

到目前为止,您的方向是正确的。

坚持使用您已有的代码,这里是 advanceTimer 方法应该如何使其工作:

- (void)advanceTimer:(NSTimer *)timer
{
    [countdown setIntegerValue:([countdown integerValue] - 1)];
    if ([countdown integerValue] == 0)
    {
        // code to stop the timer
    }
}

编辑: 为了使整个事情更加面向对象,并避免每次都从字符串转换为数字并返回,我会做这样的事情:

// Controller.h:
@interface Controller
{
    int counter;
    IBOutlet NSTextField * countdownField;
}
@property (assign) int counter;
- (IBAction)startCountdown:(id)sender;
@end

// Controller.m:
@implementation Controller

- (IBAction)startCountdown:(id)sender
{
    counter = 60;

    NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                         target:self
                                       selector:@selector(advanceTimer:)
                                       userInfo:nil
                                        repeats:YES];
}

- (void)advanceTimer:(NSTimer *)timer
{
    [self setCounter:(counter -1)];
    [countdownField setIntegerValue:counter];
    if (counter <= 0) { [timer invalidate]; }
}

@end

而且,如果您可以使用绑定(bind),您可以简单地将文本字段的 intValue 绑定(bind)到 Controllercounter 属性。这将允许您删除类接口(interface)中的 IBOutletadvanceTimer 中的 setIntegerValue: 行。

更新:删除了两次将计时器添加到运行循环的代码。感谢 Nikolai Ruhe 和 nschmidt 注意到该错误。

更新:根据 nschmidt,使用 setIntegerValue 方法简化代码。

编辑: (void)advanceTimer:(NSTimer *)timer 定义中的拼写错误......导致恼人的“无法识别的选择器发送到实例”异常

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

相关文章:

swift - 如何通过 Swift 正确测试 NSEventModifierFlags 中的某些值?

cocoa - 将 NSWindow contentViewController 替换为具有相同窗口大小的新 ViewController

cocoa-touch - NSManagedObjectContextDidSaveNotification 在 iOS 7 中未触发

objective-c - 对象分配初始化不规则

cocoa - 更改 NSTableView 中的 'enter' 关键行为

objective-c - iOS:XCode 4.4.1:xcodebuild 错误 - 无法从文件读取诊断信息

iphone - 从 UIWebView 或 UIView 获取 PDF/PNG 作为输出

objective-c - 试图将 RowAtIndexPath 移动到另一个部分,iOS

ios - 键盘在 ios 中显示方向错误

iphone - 一个简单的 viewDidLoad 问题