简体   繁体   中英

How to call method with delay and in background thread

I have a method what I want to call after -viewDidLoad and in background thread. Is there way to combine this two methods:

[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]

and

[self performSelectorInBackground:(SEL) withObject:(id)] ?

Grand Central Dispatch has dispatch_after() which will execute a block after a specified time on a specified queue. If you create a background queue, you will have the functionality you desire.

dispatch_queue_t myBackgroundQ = dispatch_queue_create("com.romanHouse.backgroundDelay", NULL);
// Could also get a global queue; in this case, don't release it below.
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);
dispatch_after(delay, myBackgroundQ, ^(void){
    [self delayedMethodWithObject:someObject];
});
dispatch_release(myBackgroundQ);

Try the following:

// Run in the background, on the default priority queue
dispatch_async( dispatch_get_global_queue(0, 0), ^{
    [self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
});

Code not tested

Be aware that your selector/method must not use UIKit (so don't update the UI) or access UIKit properties (like frame) so your selector may need to kick off work back to the main thread. eg

(id)SomeMethod:UsingParams: {

    // Do some work but the results

    // Run in the background, on the main queue
    dispatch_async(dispatch_get_main_queue(), ^{
        // Do something UIKit related
    });
}
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]

Performs a selector on the thread that it is being called. So when you call it from a background thread it will run there...

You can do that per example:

dispatch_time_t delay = dispatch_time( DISPATCH_TIME_NOW, <delay in seconds> * NSEC_PER_SEC );
dispatch_after( delay, dispatch_get_main_queue(), ^{
    [self performSelectorInBackground: <sel> withObject: <obj>]
});

Somehow a mixed solution. It would be better to stick with a full GCD approach tho.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM