I've recently been trying to understand the importance of blocks in programming (Objective-C in particular). They're obviously used quite a lot in iOS/Cocoa APIs, so I'm trying to understand them.
Mostly, I still don't understand why you would use a block versus just creating a separate helper function. For example, if I create a block that implements some sorting function, wouldn't it be easier to create that function as a method of a helper class so all objects in the code could use it more easily?
A nice feature of blocks is that they can be used wherever objects can be used, so you can e.g. store blocks in an array or dictionary. Another interesting thing is that you can pass blocks within an object or between objects as method arguments, e.g.:
The second method is even a
UIView
API. One could argue that function pointers would do here, but that would be more complicated, less flexible and incoherent. Also, blocks can access local variables and instance variables without passing them as arguments.That's my 2 cents from blocks user point of view, but I'm none of an expert...
Blocks are a nice alternative to callbacks or delegates, if for nothing else than improving code readability by keeping your business logic local to the calling code.
But they're so much more: highly useful for asynchronicity, and a necessity if you want to use GCD to improve performance.
Other than Apples official docs, I can highly recommend reading the excellent Practical Blocks by Mike Ash.