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 function when I need that code to run?
The __block Storage Type __block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable's lexical scope.
You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.
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.
As Brad Larson comments in response to this answer:
Blocks will let you define actions that take place in response to an event, but rather than have you write a separate method or function, they allow you to write the handling code right where you set up the listener for that event. This can save a mess of code and make your application much more organized.
A good example of which i can give you is of alert view, it will be good if i decided at time of creation of alert view what will happen when i dismiss that instead i write the delegate method and wait for that to call. So it will be much easier to understand and implement and also it provides fast processing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With