Duck
Duck

Reputation: 35993

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];
myblock();

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];
myblock();

// 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?

Upvotes: 3

Views: 2184

Answers (1)

user529758
user529758

Reputation:

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];
}

Usage:

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

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

Upvotes: 5

Related Questions