Objective-C blocks - Example and a Quick reference

This post is inspired by following Tweet when it was mentioned after years of experience, developer still could not remember the blocks syntax.


  • If you want to declare block as a property

    First use typedef to declare block parameters and return type as follows
    (The block we are about to declare takes NSInteger as an input and returns converted NSString object back)

    
      typedef NSString*(^StringConverter)(NSInteger);
      

Now declare a property for a given block definition,

    @property (nonatomic, strong) StringConverter stringToIntConverterBlock;
    

> Some people mentioned to use `copy` for block. But after going through several blog posts and StackOverflow answers, I came to conclusion that it is ok to declare it as `strong` as long as you are using ARC.
  • If you want to pass a block as a method parameter

After defining block and declaring it as a property, you can pass it to any method as follows,


- (void)convertNumber:(StringConverter)converter {
    // Method definition
    converter(100)
}

And that should be it. You have defined block, declared it as a property and passed it as a parameter to the method.

I am glad to say I am one of the people referenced by the Tweet and hope this short blog post helps someone some day. (Including me of course!)

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!