How to send a message or notification to main thread in Xcode?

笑着哭i 提交于 2019-12-02 03:04:31

The problem is merely your use of dispatch_sync, which blocks. That's why you're being killed. You almost had it right. What you want is:

// ... task 1 on main thread
dispatch_async(other_queue, ^{
    // ... task 2 in background thread
    dispatch_async(dispatch_get_main_queue(), ^{
        // ... task 3 on main thread
    });
});

That is the standard pattern for getting off the main thread and coming back on. That's all there is to it!

What you want to achieve will be done easier by using NSOperation's and NSOperationQueue's instead of the GCD. It doesn't fire notifications, but I believe it does what you want to do.

If I am understanding your problem correctly, you are currently running task1 in the main thread. Task2 is later fired concurrently via task1, but task2 tells task3 to call the UI. So in other words, task2 and task3 depend on task1, right?

Using NSOperations (An operation is a piece of code, either a selector or a block, that you can run in a different thread) and NSOperationQueues, you can achieve those dependencies in less than a minute.

//Assuming task1 is currently running.
NSOperationQueue *downloadAndUpdate; //Leaving out initialization details.

NSOperationBlock *task2; //Leavign out initialization details.
NSOperationBlock *task3;

//This is where it gets interesting. This will make sure task3 ONLY gets fired if task2 is finished executing.
[task3 addDependency:task2];

//Task3 could have the following code to update the main thread.

[[NSOperationQueue mainQueue] addOperation:myUIUpdatingTask];

These APIs are at a higher level than the GCD, and I definitely recommend you learn how to use them to create better concurrency.

Here's a tutorial To help you get started with these APIs.

(DISCLOSURE: I'm the author of this post, but I promise my intention is not to advertise my work. I wrote this tutorial because I needed a better way to do concurrency than the GCD and ended up learning this. I like to teach what I learn).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!