Search code examples
objective-cgrand-central-dispatchdispatch-async

dispatch_async without using a block


I want to use dispatch_async to occasionally pull a changing resource from my web server (about every 60 seconds).

I want to make use of dispatch_async but I want to give it a function name instead. Since I want that function to sleep and redo the same thing again.

This is what I am trying to do dispatch_async(self.downloadQueue, @selector(getDataThread:)); (this does not compile)

I think a while loop is not a good idea so I'm wondering what was the best approach for this


Solution

  • How about something like...

    NSTimer *timer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(getDataThread:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    - (void)getDataThread:(id)foo {
        dispatch_async(self.downloadQueue, ^{
           // code you want to run asynchronously
        });
    }
    

    It seems you want some block of code to run asynchronously... but you want that to also run at a timed interval, so I think this should suffice.

    If you want to ditch blocks and dispatch_async altogether you could look at NSOperationQueue, keeping in mind NSOperationQueue is built on GCD but you don't need to worry about interfacing with it directly.