【问题标题】:Xcode cocoa simultaneously update interface by timer and continuous action by sliderXcode cocoa 通过定时器同时更新界面和通过滑块连续动作
【发布时间】:2013-12-25 14:03:45
【问题描述】:

我需要通过计时器更新一些用户界面对象,但是当我通过连续动作触摸滑块时,所有内容都冻结在滑块旁边。 在 iOS 这个版本工作正常,但在 mac os x 一些问题:(

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    tick = 0;

    [NSTimer scheduledTimerWithTimeInterval:0.25f
                                     target:self
                                   selector:@selector(timerTick)
                                   userInfo:nil
                                    repeats:YES];
}

- (void)timerTick
{
    tick++;
    [self.labelTest setIntegerValue:tick];
}

- (IBAction)sliderAction:(id)sender
{
    // do something 
    NSLog(@"%g", [self.sliderMain doubleValue]);
}

【问题讨论】:

    标签: objective-c cocoa continuous simultaneous


    【解决方案1】:

    您应该将计时器添加到主运行循环:

    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    

    你还应该创建实例变量或属性,例如:

    @property (strong, nonatomic) NSTimer *timer;
    

    在您创建计时器之前,我建议您使用延迟初始化:

    if (!_timer) {
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.25f
                                         target:self
                                       selector:@selector(timerTick)
                                       userInfo:nil
                                        repeats:YES];
        }
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    

    当您关闭应用程序或应用程序进入后台时,您可以使计时器无效:

    [self.timer invalidate];
    self.timer = nil;
    

    希望对您有所帮助。

    【讨论】:

    • 不知道你在默认运行循环模式下安排了两次定时器是不是有点低效?如果您要在常用模式下添加计时器,您可以使用不安排计时器的方法之一创建计时器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2015-04-12
    • 2014-05-30
    相关资源
    最近更新 更多