简体   繁体   中英

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

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

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.

NSNotificationCenter allows messaging between threads. You set up a 'listener' and can then broadcast notifications - the Apple documentation is very good, and it's easy to pick up.

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