Sending messages from background thread to main thread on iOS

ios, iphone, multithreading, objective-c, xcode

Solution

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];

Problem

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. } ```

Original source