converting NSTimer running not on main runloop to GCD

Posted by Justin Galzic on Stack Overflow See other posts from Stack Overflow or by Justin Galzic
Published on 2010-12-26T20:47:54Z Indexed on 2010/12/26 20:54 UTC
Read the original article Hit count: 273

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?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c