objective-c - Objective-C 如何制作一个从两分钟开始倒计时的计时器?

标签 objective-c ios xcode timer nstimer

我在互联网上搜索了答案,但一无所获。我试过了

- (void)viewDidLoad {

[super viewDidLoad];

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

- (void)timer {
for (int totalSeconds = 120; totalSeconds > 0; totalSeconds--){

timerLabel.text = [self timeFormatted:totalSeconds];

if ( totalSeconds == 0 ) {

   [twoMinTimer invalidate];

   } } }

但它没有用,当我转到那个 View 时,标签从 2.00 变为 0.01,然后就停止了。

任何建议将不胜感激 - 菲利普

最佳答案

您使用的是一次性 for 循环,而不是简单地减少总时间。试试这个:

- (void)viewDidLoad {

    [super viewDidLoad];
    totalSeconds = 120;
    twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(timer)
                                                 userInfo:nil
                                                  repeats:YES];
}

- (void)timer {
    totalSeconds--;
    timerLabel.text = [self timeFormatted:totalSeconds];
    if ( totalSeconds == 0 ) {
        [twoMinTimer invalidate];
    } 
}

totalSeconds 声明为 int。

编辑:非常感谢@JoshCaswell 和@MichaelDorst 分别提供的建议和代码格式。 NSTimer 绝不是时间的准确表示,对于秒表或计数器来说绝对不够准确。相反,NSDate 的 +dateSinceNow 将是一个更准确的替代品,甚至逐渐降低级别的 CFAbsoluteTimeGetCurrent()mach_absolute_time() 也可以准确到 sub -毫秒

关于objective-c - Objective-C 如何制作一个从两分钟开始倒计时的计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11377616/

相关文章:

ios - 使用 MKNetworking 图像上传 PHP 获取内部错误 500

ios - @""到底在幕后做了什么?

ios - 如何在 iOS 中获取 iPod 库中歌曲的文件位置

ios - 按下按钮后如何在屏幕事件的同时播放声音

ios - SpriteKitPhysicsBody非矩形碰撞

c - 如何在 Objective-C/ANSI C 中创建用于对象实例化的宏

ios - 关于插入和删除单元格的 UITableView 动画问题

iphone - 保存和显示 textfield.text

ios - Xcode AMSlideMenu 在某些屏幕中禁用菜单

objective-c - 阻止我的 iOS 8 iPad 操作表忽略它的父 ViewController?