Create my own completion blocks in iOS

前端 未结 2 1989
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 22:37

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

<         


        
2条回答
  •  旧时难觅i
    2021-01-02 22:51

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

提交回复
热议问题