Using Block in Objective C by example

Overview

Say we have a class called SPFPriceFetcher that uses JCDHTTPConnection.

SPFPriceFetcher
|
|—JCDHTTPConnection

JCDHTTPConnection uses NSURLConnection connection where any data, finish loading, or response received would have to give feedback BACK to SPFPriceFetcher. We give feedback by retaining and using block definitions passed in from SPFPriceFetcher.

Passing block definitions from parent (SPFPriceFetcher) to child (JCDHTTPConnection)

Basically what happens is that SPFPriceFetcher provides block definitions for JCDHTTPConnection to retain and use:

SPFPriceFetcher — OnSuccess block definition —-> JCDHTTPConnection
SPFPriceFetcher — OnFailure block definition —-> JCDHTTPConnection
SPFPriceFetcher — OnDidSendData block definition —-> JCDHTTPConnection

where the block interface is defined in JCDHTTPConnection.h as:

Using blocks

1) When you declare a method interface that takes such block definitions, you need to have the block interface as defined by the typedefs above.

JCDHTTPConnection.h

Then in your block definition, you would use the block definitions as a variable. In our definition, we retain them:

JCDHTTPConnection.m

Now when the NSURLConnection runs to connectionDidFinishLoading, we use our retained block definitions and call them:

For example, self.onSuccess will call the block definitions you retained that was passed in from SPFPriceFetcher earlier. It will pass the needed parmaters NSHTTPURLResponse (self.response) and NSString * (self.body) in for it to process.

In SPFPriceFetcher.m, we pass in the block definition like so:

As you can see, when we provide block definitions, we simply use “^” to denote that its a block, and then use the block interface and continue with the code implementation. We just have to make sure to match the block interface.

For example, in our case we know that OnSuccess block takes is defined as:

OnSuccess block definition

and thus, we first denote “^” as a block, then match the block interface by having the parameters be NSHTTPURLResponse and NSString. We then write the method implementation.

OnSuccess block definition we pass in:

OnFailure block definition

Same thing with the OnFailure block definition.
We first note “^” to denote that its a block definition. Then we provide the interface needed by the OnFailure block definition as shown:

OnFailure block definition we pass in: