I have an iOS app where I am completing tasks on the background thread. As each task is completed I want to send a message to the main thread so I can move along my custom progress bar to the appropriate stage.
What is the simplest, yet most secure way to achieve this?
EDIT 1
This is the method I am using:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
// get background tasks done.
[self.background backgroundMethod];
});
EDIT 2
Here is an example of what I would attempt using @Madboy's answer. Within the class where I perform methods in the background I have a pointer to my progress bar. Do we think this would work? (Please note the change also to EDIT 1).
@implementation BackgroundClass
@synthesize delegate;
@synthesize customProgressBar
- (void)backgroundMethod
{
// Run tasks
}
- (void)delegateSaysBackgroundMethodIsFinished
{
[self performSelectorOnMainThread:@selector(tasksDone:) withObject:self.customProgressBar waitUntilDone:NO];
}
@implementation CustomProgressBar
- (void)tasksDone
{
// change UI to reflect progress done.
}
You can use performSelectorOnMainThread:withObject:waitUntilDone:
method of NSObject.
The waitUntilDone parameter is a bool. You can pass YES to make your background thread wait until the method on main thread is done. You can pass NO to just fire that method and continue execution on background thread simultaneously with the main thread.
This is based on what you are doing. Are you performing tasks in the background with GCD? Then you simply can call:
dispatch_async(dispatch_get_main_queue(), ^{
//your main thread task here
});
If you are running in an NSThread you could do this:
[myObject performSelectorOnMainThread:YOURSELECTOR withObject:YOUROBJECT waitUntilDone:NO];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With