Create my own completion blocks in iOS

痴心易碎 提交于 2019-11-29 20:29:19

问题


I have an object which takes a long time to do some stuff (it downloads data from a server).

How can I write my own completion block so that I can run...

[downloader doSomeLongThing:^(void) {
    //do something when it is finished
}];

I'm not sure how to save this block in the downloader object.


回答1:


You can copy the block then invoke it:

typedef void (^CallbackBlk)();

@property (copy) CallbackBlk cb;

- (void)doSomething:(CallbackBlk)blk
{
    self.cb = blk;

    // etc.
}

// when finished:
self.cb();



回答2:


Since you're not using any parameters in your callback, you could just use a standard dispatch_block_t and since you just want to call back to it when your long process has completed, there's no need to keep track of it with a property. You could just do this:

- (void)doSomeLongThing:(dispatch_block_t)block
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Perform really long process in background queue here.

        // ...

        // Call your block back on the main queue now that the process 
        // has completed.
        dispatch_async(dispatch_get_main_queue(), block);
    });
}

Then you implement it just like you specified:

[downloader doSomeLongThing:^(void) {
    // do something when it is finished
}];


来源:https://stackoverflow.com/questions/14586641/create-my-own-completion-blocks-in-ios

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