使用将在主线程上运行的块调用模型方法 [英] Invoke model method with block that will run on the main thread

查看:78
本文介绍了使用将在主线程上运行的块调用模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最新应用程序架构的核心原则之一是,我将在应用程序模型上调用方法,这些方法将是异步并接受失败和成功场景块。

one of the central tenets of the architecture of my latest app is that I'm going to call methods on the app's model which will be async and accept failure and success scenario blocks.

ie,UI调用模型方法有2个块,一个用于成功,一个用于失败。

i.e., The UI calls the model method with 2 blocks, one for success and one for failure.

这很好,因为原始调用的上下文但是,保留了块本身在后台线程上调用。无论如何在主线程上调用一个块??

This is great because the context of the original call is retained, however, the block itself is called on the background thread. Is there anyway of calling a block on the main thread??

希望我已经将它表示好了,如果没有,基本上,我的模型方法是异步的,立即返回并创建一个运行op的新线程。一旦op返回,我将调用一个块,该块将对返回的数据进行后处理,然后我需要为UI内部调用的成功场景调用块。但是,UI中定义的成功和失败场景块应该在主线程中调用,因为我需要与UI元素进行交互,这些元素只能在我认为的主线程上完成。

Hopefully I have explianed it ok, if not, basically, my model methods are async, return immediately and create a new thread on which to run the op. Once the op returns I will invoke a block which will postprocess the returned data, THEN i need to call the block for the success scenario defined by the called inside the UI. However, the success and failure scenario blocks defined in the UI should be called in the main thread because I need to interact with UI elements which should only be done on the main thread I believe.

非常感谢

推荐答案

这样的事情可能就是你所追求的:

Something like this is probably what you're after:

- (void) doSomethingWhichTakesAgesWithArg: (id) theArg
                            resultHandler: (void (^)(BOOL, id, NSError *)) handler
{
    // run in the background, on the default priority queue
    dispatch_async( dispatch_get_global_queue(0, 0), ^{
        id someVar = [theArg computeSomething];

        NSError * anError = nil;
        [someVar transmuteSomehowUsing: self error: &anError];

        // call the result handler block on the main queue (i.e. main thread)
        dispatch_async( dispatch_get_main_queue(), ^{
            // running synchronously on the main thread now -- call the handler
            handler( (error == nil), theArg, anError );
        });
    });
}

这篇关于使用将在主线程上运行的块调用模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆