Create my own completion blocks in iOS

I have an object that takes a long time to do some things (it downloads data from the server).

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

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

I am not sure how to save this block in the loader object.

+6
source share
2 answers

You can copy the block and call it:

 typedef void (^CallbackBlk)(); @property (copy) CallbackBlk cb; - (void)doSomething:(CallbackBlk)blk { self.cb = blk; // etc. } // when finished: self.cb(); 
+10
source

Since you do not use any parameters in your callback, you can simply use the standard dispatch_block_t, and since you just want to call it back when your long process is complete, there is no need to track 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 the same way you specified:

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

All Articles