Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages from background thread to main thread on iOS

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. 
}
like image 297
Eric Brotto Avatar asked Oct 17 '12 11:10

Eric Brotto


2 Answers

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.

like image 44
basar Avatar answered Oct 22 '22 11:10

basar


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];
like image 161
Michael Ochs Avatar answered Oct 22 '22 10:10

Michael Ochs