iphone - 在 iOS 上从后台线程向主线程发送消息

标签 iphone objective-c ios xcode multithreading

我有一个 iOS 应用程序,我在其中完成后台线程上的任务。当每个任务完成时,我想向主线程发送一条消息,以便我可以沿着我的自定义进度条移动到适当的阶段。

实现此目标的最简单但最安全的方法是什么?

编辑 1

这是我正在使用的方法:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 
                                         (unsigned long)NULL), ^(void) {

     // get background tasks done. 
     [self.background backgroundMethod];

});

编辑 2

这是我尝试使用@Madboy 的回答的示例。在我在后台执行方法的类中,我有一个指向进度条的指针。我们认为这行得通吗? (请注意对 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. 
}

最佳答案

这取决于你在做什么。您是否使用 GCD 在后台执行任务?然后你可以调用:

dispatch_async(dispatch_get_main_queue(), ^{
    //your main thread task here
});

如果您在 NSThread 中运行,您可以这样做:

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

关于iphone - 在 iOS 上从后台线程向主线程发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12933397/

相关文章:

ios - 使用特定键对NSArray进行排序

ios - 使用 dateFormat Swift 将日期转换为日期

iphone - iPhone 只能使用 SQLite 数据库吗?

iphone - 使用 UIPopover 从图库中获取图像并显示它

ios - 图书馆对图书馆的引用

ios - Xcode:在 Instruments 中未发现僵尸

ios - 如何在iOS的SQLite数据库中更新图像?

iphone - 在 Xcode 4.2 和 iOS SDK 5.0 中使用 gcc 4.2

iPhone XCode 创建与日期相关的 if 语句

iphone - 将图像数组添加到 ScrollView Objective-C