Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you append code to an Objective-C block variable?

I want to dynamically add code to a block variable, or merge or concatenate a block with another block. Is this possible?

like image 744
eric Avatar asked Sep 16 '26 06:09

eric


1 Answers

One way of doing it is creating a block that calls the block to be "expanded" before performing its own functions.

For example, consider the example below that adds logging functionality to an arbitrary block passed into it:

typedef void (^MyBlock)(int);

-(MyBlock) expand:(MyBlock)nested {
    return ^(int x) {
        nested(x);
        NSLog("The value of x = %d", x);
    };
}

The cumulative effect of calling the block produced by expand: is that of invoking the original block, followed by an operation from the expanded block. You can take it further, to create an appendBlock method:

-(MyBlock) appendBlock:(MyBlock)second toBlock:(MyBlock)first {
    return ^(int x) {
        first(x);
        second(x);
    };
}
like image 182
Sergey Kalinichenko Avatar answered Sep 21 '26 01:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!