【问题标题】:NSTimer calls the selector method twice on the same thread?NSTimer 在同一个线程上两次调用选择器方法?
【发布时间】:2011-08-31 13:24:13
【问题描述】:

1) 我在 viewdidload 上创建了一个 NSTimer

#ifndef NDEBUG
    NSLog(@"************In viewDidLoad method initializng timer [%@]",[NSThread currentThread]);
#endif
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(onTimerKicks:) userInfo:clues repeats:YES];

2) 选择器回调执行一些条件逻辑(视频播放时间)。问题是每次定时器唤醒它都会为同一个线程上的同一个实例调用选择器方法两次!!!我怎么知道 ? NS 日志语句打印线程详细信息和调试。

- (void) onTimerKicks:(NSTimer *) timer
{

    if (currentPlaybackTime == 10) {

#ifndef NDEBUG
        NSLog(@"[%@] ************calling onTimerKicks:onAutoPageTimer from onTimer current playbacktime = %d", [NSThread currentThread], currentPlaybackTime);
#endif

    }
}

3) 这是一次唤醒定时器的调试

2011-08-30 19:11:51.759 MASLTales[7735:207] ************In viewDidLoad method initializng timer [<NSThread: 0x580f3a0>{name = (null), num = 1}]
2011-08-30 19:12:05.760 MASLTales[7735:207] [<NSThread: 0x580f3a0>{name = (null), num = 1}] ************ccalling onTimerKicks:onAutoPageTimer from onTimer current playbacktime = 10
2011-08-30 19:12:06.260 MASLTales[7735:207] [<NSThread: 0x580f3a0>{name = (null), num = 1}] ************ccalling onTimerKicks:onAutoPageTimer from onTimer current playbacktime = 10

有人知道为什么我总是两次看到这条消息吗? 提前致谢。

【问题讨论】:

    标签: ios nstimer


    【解决方案1】:

    实际上它没有调用选择器两次,它是连续调用选择器,因为在初始化计时器时你已经写了repeats:YES];. 但是在你的选择器中有一个条件块,它只在 1 秒内为真,你的计时器正在触发选择器每半秒。所以它打印了两次。

    【讨论】:

    • 发誓很快。我将计时器增加到每 2 秒一次。现在一切都说得通了。非常感谢'saadnib'
    猜你喜欢
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2021-02-28
    相关资源
    最近更新 更多