user2070259 user2070259 - 5 months ago 45
iOS Question

How do I create my own completion handler as part of method parameters

I want to create a completion handler for a certain class, instead of firing off the class's main code and waiting for a delegate callback. I've read through the Apple documentation and they don't seem to give a very good example of how to directly implement something like this.


You need to treat the completion block just like a variable. The method will accept a block as part of it's parameters, then store it for later.

- (void)myMethodWithCompletionHandler:(void (^)(id, NSError*))handler;

You can typedef that block type for easier reading:

typedef void (^CompletionBlock)(id, NSError*);

And then store your block as an instance variable:

In your @interface: CompletionBlock _block;

In the myMethod.. _block = [handler copy]

Then when you want the completion block to execute you just call it like a regular block:

_block(myData, error);