Storing a block with a parameter inside a NSArray

I know I can define a property like a block, something like:

self.myProperty = ^(){
   // bla bla bla        

store that on an array doing

NSArray *arrayOfBlocks = [[NSArray alloc] initWithObject:[self.myProperty copy]];

and then execute it using

void (^ myblock)() = [arrayOfBlocks objectAtIndex:0];

but what about if the block has a parameter?

I mean, a block like this one:

self.myProperty = ^(id myObject){
   // bla bla bla        

What I want is being able to keep this lines unchanged

void (^ myblock)() = [arrayOfBlocks objectAtIndex:0];

// yes, I know I can replace myblock(); with myblock(object);
// but because I have a large number of blocks on this array, I will have to build
// a huge if if if if statements to see what block is being run and change the objects passed

What I want is to store the block with the parameter on the array... something like this:

NSArray *arrayOfBlocks = [[NSArray alloc] initWithObject:[self.myProperty(object?) copy]];

is this possible?


Fortunately, blocks are first-class values. You can make a factory method that returns a block which will be invoked with a certain object.

typedef void (^CallbackBlock)(void);
- (CallbackBlock)callbackWithNumber:(int)n
    return [^{
        NSLog(@"Block called with %d", n);
    } copy];


[mutableArray addObject:[self callbackWithNumber:42]];
[mutableArray addObject:[self callbackWithNumber:1337]];

// later:
CallbackBlock cb = [mutableArray objectAtIndex:0];

Need Your Help

How to theme the header bar close button in GTK+3?

gtk themes gtk3

I'd like to change the style of the close button on GTK+3 windows with so called "header bars", where the window is rendered without decoration and GTK composes title bar and widgets.

Refresh an element in Javascript

javascript refresh element

Thanks to How to refresh/reload page once using jQuery? answer I could solve an issue.