문제

I have a task that runs periodically and it was originally designed to run on a separate run loop than the main runloop using NSThread and NSTimer.

What's the best way to adapt this to take advantage of GCD?

Current code:

-(void)initiateSomeTask
{
    [NSThread detachNewThreadSelector:@selector(startTimerTask) 
            toTarget:self withObject:nil];
}

-(void)startTimerTask
{
    // We won't get back the main runloop since we're on a new thread 
    NSRunLoop *myRunLoop = [NSRunLoop currentRunLoop]; 

    NSPort *myPort = [NSMachPort port];
    [myRunLoop addPort:myPort forMode:NSDefaultRunLoopMode];

    NSTimer *myTimer = [NSTimer timerWithTimeInterval:10 /* seconds */ 
            target:self selector:@selector(doMyTaskMethod) 
            userInfo:nil repeats:YES];

    [myRunLoop addTimer:myTimer forMode:NSRunLoopCommonModes];
    [myRunLoop run];
}

Is there anything I can do besides replace detachNewThreadSelector with dispatch_async?

도움이 되었습니까?

해결책

You can replace the use of NSTimer with use of dispatch_source_create with DISPATCH_SOURCE_TYPE_TIMER. You won't need a run loop then.

Back in the original case, though, you don't really need to make a thread or use dispatch to run a timer. Kind of the point of run loops is that you don't need to make a thread to do something simple like a timer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top