简体   繁体   English

在iOS上将消息从后台线程发送到主线程

[英]Sending messages from background thread to main thread on iOS

I have an iOS app where I am completing tasks on the background thread. 我有一个iOS应用程序,我在后台线程上完成任务。 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 编辑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 编辑2

Here is an example of what I would attempt using @Madboy's answer. 这是我尝试使用@Madboy答案的一个例子。 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). (请注意对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? 您是否在后台使用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: 如果你在NSThread中运行,你可以这样做:

[myObject performSelectorOnMainThread:YOURSELECTOR withObject:YOUROBJECT waitUntilDone:NO];

You can use performSelectorOnMainThread:withObject:waitUntilDone: method of NSObject . 您可以使用performSelectorOnMainThread:withObject:waitUntilDone: NSObject的方法。

The waitUntilDone parameter is a bool. waitUntilDone参数是一个bool。 You can pass YES to make your background thread wait until the method on main thread is done. 您可以传递YES以使后台线程等到主线程上的方法完成。 You can pass NO to just fire that method and continue execution on background thread simultaneously with the main thread. 您可以传递NO以仅触发该方法并在主线程上同时在后台线程上继续执行。

NSNotificationCenter allows messaging between threads. NSNotificationCenter允许线程之间的消息传递。 You set up a 'listener' and can then broadcast notifications - the Apple documentation is very good, and it's easy to pick up. 您设置了一个“监听器”,然后可以广播通知 - Apple文档非常好,并且很容易上传。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM