In programming, what differentiates a good developer from a great developer is the way each one takes advantage of the programming tools he or she offered by the used language. Objective-C, the official language for developing applications for iPhone, iPad and Mac OS, is a multi-featured one, and as a relative to C, very powerful. New developers have a lot to explore when starting working with it, while advanced programmers have always something new to learn, as there are numerous supported programming aspects. One of them, is the capability to write code using Blocks.
Well, a block is a self-contained, autonomous code fragment, existing always into the scope of another programming structure, as for example the body of a method. The code on the block can “interact” with the world out of it, but what takes place in the block is not visible to the scope out of it. Also, blocks can modify the values of variables being out of its body using a special way (we’ll see more later). Blocks have two great features:
- They can be executed in a later time, and not when the code of the scope they have been implemented is being executed.
- Their usage leads eventually to a much cleaner and tidier code writing, as they can be used instead of delegate methods, written just in one place and not spread to many files.
Focusing even more on the second feature, blocks offer a nice solution for creating callbacks instead of delegates, as they are declared and implemented directly to the point of the code where they are invoked. Using blocks, there is no need to adopt protocols, or implementing delegate methods that lead to much more code in a class. The best thing though, is that the callback procedure can directly access and use any variables existing locally in the scope where the block has been defined, so the need of passing data like we do in callback methods is eliminated. However, blocks cannot totally replace delegates as they cannot be used for every purpose. The best practice is to make combination of both, and that can be achieved both by following some simple rules and using the experience obtained in time.