从计时器显示NSTextField中的文本

时间:2013-05-08 22:34:37

标签: objective-c macos

我正在使用

[NSTimer scheduledTimerWithTimeInterval: _callbackPeriod
                                 target: self
                               selector: @selector(timerCallback:)
                               userInfo: nil
                                repeats: NO];

计时间隔。这个间隔可能会有所不同,但我在1秒内测试它。在每个间隔(1秒)结束时,更新一个简单的UI文本框,然后再次安排计时器。通过

调用更新
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSNotification *notification = [NSNotification notificationWithName:named 
                                                             object:info];
[notificationCenter postNotification:notification];

通知代码执行

NSString* timerString = [NSString stringWithFormat:@"%i", info.timerCount];
[_timerValue setStringValue:timerString];

其中

@property (weak) IBOutlet NSTextField *timerValue;

此方法将显示一个运行计数器,只要间隔结束,该计数器就会递增。

我遇到的问题是数据的显示速度很慢。我应该看到间隔的平滑显示随着它的进展而变得不稳定。 NSLogs表明数据确实是平滑的,但显示不是。因此,我没有显示1,2,3,4 5等,而是看到1,3,4,6 ......我知道我做错了什么?我在setStringValue周围需要一些糖吗?

感谢。

1 个答案:

答案 0 :(得分:0)

以下是倒数计时器的示例,应该可以帮到你。

- (void)startCountdown {
    countdownSeconds = 60; 
    startTime = [NSDate date];

    countdown = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
    selector:@selector(countdownUpdateMethod:) userInfo:nil repeats:YES];

    // invalidate the timer if the view unloads before the end
    // also release the NSDate if it does not reach the end
}

- (void)countdownUpdateMethod:(NSTimer*)theTimer {

    NSDate *currentDate = [NSDate date];
    NSTimeInterval elaspedTime = [currentDate timeIntervalSinceDate:startTime];

    NSTimeInterval difference = countdownSeconds - elaspedTime;
    if (difference <= 0) {
        [theTimer invalidate];  // kill the timer
        difference = 0;
    }

    // Update the label with the remaining seconds
    NSString *countdownString = [NSString stringWithFormat:@"%f",difference];

    countdownLabel.text = [countdownString substringToIndex:2];
   // NSLog(@"%f",difference);
}