An Array of Blocks?

nsarray, objective-c, objective-c-blocks

Solution

Putting Blocks into `NSArray`s is fine; they're objects. In fact, they inherit from `NSObject`.

You do need to copy, them, however. Those Blocks are created on the stack and need to be moved to the heap in order to live past the end of the current method. If you're using ARC, this is easy:

NSArray *array = [NSArray arrayWithObjects:[^{NSLog(@"Block 1");} copy], ...

Under MRR, you need to balance that `copy`, so you have two unpleasant options: use temps, or enumerate the array right after creating it and send `release` to all its members.

Sending `invoke`, on the other hand, isn't completely kosher, because that's a private method. The only fully-API-compliant way to invoke a Block is with function-call syntax:

typedef GenericBlock dispatch_block_t;
for( GenericBlock block in array ){
    block();
}

Problem

This seems like a very strange interaction to me but at the same time it not only works but throws no warnings or errors in the process. Just looking to get some better understanding of blocks in general and why something like this could be right or wrong. Is there any reason why something like this shouldn't be done? ``` NSArray *array = [NSArray arrayWithObjects:^{NSLog(@"Block 1");}, ^{NSLog(@"Block 2");}, ^{NSLog(@"Block 3");}, nil]; for (id block in array) { [block invoke]; } ```

Original source