Reputation: 2552
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)]
?
Upvotes: 14
Views: 13523
Reputation: 5891
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. e.g.
(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
});
}
Upvotes: 7
Reputation: 5558
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.
Upvotes: 2
Reputation: 64002
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);
Upvotes: 23
Reputation: 15213
[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...
Upvotes: 4