NSTimer要求我将它添加到runloop

chi*_*ken 19 objective-c nstimer nsrunloop ios

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

以下是我的问题示例:

#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];
}
Run Code Online (Sandbox Code Playgroud)

编辑: 我相信我措辞很差.如果我打电话,我想知道为什么 [[NSRunLoop currentRunLoop] addTimer:_busTimer forMode:NSRunLoopCommonModes];有必要.如果我不包括该行,则计时器不会触发.startTimersomeMethodBeginCalled

如果我呼吁startTimer来自viewDidLoad例如,我可以删除NSRunLoop线和计时器将每隔60秒射击.

Rud*_*vič 21

以下是如何添加NSTimer到runloop:

NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
Run Code Online (Sandbox Code Playgroud)

  • OP正在询问是否将计时器添加到运行循环中,而不是如何将计时器添加到运行循环中. (2认同)

bor*_*den 14

您可以始终使用此方法:

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

这将为您节省一条线,因为它会自动将其添加到运行循环中.

  • 这是正常的方法.很少手动将计时器添加到runloop.但是,您通常应将计时器保留在ivar中,以便在需要时使其无效. (6认同)