I know that a block is a reusable chunk of executable code in Objective-C. Is there a reason I shouldn\'t put that same chunk of code in a function and just called the funct
It depends on what you're trying to accomplish. One of the cool things about blocks is that they capture local scope. You can achieve the same end result with a function, but you end up having to do something like pass around a context object full of relevant values. With a block, you can do this:
int num1 = 42;
void (^myBlock)(void) = ^{
NSLog(@"num1 is %d", num1);
};
num1 = 0; // Changed after block is created
// Sometime later, in a different scope
myBlock(); // num1 is 42
So simply by using the variable num1, its value at the time myBlock was defined is captured.
From Apple's documentation:
Blocks are a useful alternative to traditional callback functions for two main reasons:
They allow you to write code at the point of invocation that is executed later in the context of the method implementation. Blocks are thus often parameters of framework methods.
They allow access to local variables. Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.