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.
After years of iOS development, I finally caved & made an xcode snip of an Obj-C block as a property. Still can never remember the syntax š
ā Jordan Morgan (@JordanMorgan10) October 26, 2016
-
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 takesNSInteger
as an input and returns convertedNSString
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!)