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];
}
Putting Blocks into
NSArrays is fine; they’re objects. In fact, they inherit fromNSObject.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:
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 sendreleaseto 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: