OGeek|极客世界-中国程序员成长平台

标题: iphone - Invoke model method with block that will run on the main thread [打印本页]

作者: 菜鸟教程小白    时间: 2022-5-28 10:47
标题: iphone - Invoke model method with block that will run on the main thread

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.

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??

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.

many thanks



Best Answer-推荐答案


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 );
        });
    });
}





欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://www.ogeek.cn/) Powered by Discuz! X3.4