NSTimer要求我将其添加到runloop [英] NSTimer requiring me to add it to a runloop

查看:180
本文介绍了NSTimer要求我将其添加到runloop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以解释为什么调度回主队列并创建重复的 NSTimer 我不得不将它添加到RUN LOOP因为太火了?即使使用 performselectorOnMainThread ,我仍然需要将它添加到RUN LOOP才能触发它。

I am wondering if someone can explain why dispatching back to the main queue and creating a repeating NSTimer I am having to add it to RUN LOOP for it too fire? Even when using performselectorOnMainThread I still have to add it to a RUN LOOP to get it to fire.

下面是我的问题的一个例子:

Below is an example of my question:

#define queue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define mainqueue dispatch_get_main_queue()

- (void)someMethodBeginCalled
{
    dispatch_async(queue, ^{
        int x = 0;
        dispatch_async(mainqueue, ^(void){
            if([_delegate respondsToSelector:@selector(complete:)])
                [_delegate complete:nil];
        });
    });
}

- (void)compelete:(id)object
{
    [self startTimer];

    //[self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:NO];
}

- (void)startTimer
{
    NSTimer timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(callsomethingelse) userInfo:nil repeats:YES];

    //NSDefaultRunLoopMode
    [[NSRunLoop currentRunLoop] addTimer:_busTimer forMode:NSRunLoopCommonModes];
}

编辑:
我相信我措辞这个问题非常糟糕。我想知道为什么 [[NSRunLoop currentRunLoop] addTimer:_busTimer forMode:NSRunLoopCommonModes]; 是必需的 startTimer 如果我打电话给 someMethodBeginCalled 。如果我不包括该行,则计时器不会触发。

I believe I worded this question very poorly. I would like to know why [[NSRunLoop currentRunLoop] addTimer:_busTimer forMode:NSRunLoopCommonModes]; is necessary in startTimer if I call someMethodBeginCalled. If I don't include that line, the timer doesn't fire.

如果我从<来自 startTimer code> viewDidLoad 例如,我可以删除 NSRunLoop 行,计时器将每隔60秒触发一次。

If I call startTimer from viewDidLoad for example, I can remove the NSRunLoop line and the timer will fire every 60 seconds.

推荐答案

您可以随时使用此方法:

You could always use this method instead:

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(getBusLocation)userInfo:nil repeats:YES];

这将节省你是一条线,因为它会自动将它添加到运行循环中。

This will save you a line, as it will add it to the run loop automatically.

这篇关于NSTimer要求我将其添加到runloop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆