2

Possible Duplicate:
Storing Blocks in an Array

I am writing an application where at times based on certain conditions I want to run certain piece of code after certain event has occurred. this code could be at multiple places accessing variables in the functions that wont be in scope when this code needs to be executed. Is it possible to store these statements as blocks inside an array and exceute them one by one when the event occurs. If yes, how do I access variables of the previous scope?

I wanted to make this as an array of closures.

Community
  • 1
  • 1
Amogh Talpallikar
  • 12,084
  • 13
  • 79
  • 135
  • maybe but it doesn't talk about the how the local variables belonging to the scope of the outer function of those blocks will be retained. – Amogh Talpallikar Nov 19 '12 at 21:37

2 Answers2

2

You can by moving the blocks into heap by using Block_copy function on the block when you store it in your array and Block_release when you are done with it. Block_copy will move the execution block variables into heap, so that as you continue to run your app the variables won't get overwritten in stack memory.

example of using Block_copy. You need to do a bridge cast first

define a typedef for your block type in your header like so. This type example has no arguments.

typedef void (^myBlockType)();

When you want to add a block to the array you can copy the block like this:

- (void)addBlock:(void (^)())aBlock
{
        [mutableBlockArray addObject:(__bridge myBlockType)Block_copy((__bridge void *)aBlock)];
}

When you are done with the block you need to release it like this (not necessary with ARC):

id finishBlock = [mutableBlockArray objectAtIndex:index]
Block_release((__bridge void *)finishBlock);
foggzilla
  • 1,705
  • 11
  • 15
2

As @foggzilla says you need to copy the block before you can put it in an NSMutableArray (or similar).

e.g.

[myArray addObject:[myBlock copy]];

The copy selector maps straight onto the Block_copy function, so there's no need to use that. AFAIK you don't need to release the block if you're using ARC.

You must always copy the block before putting it in a collection.

Ben Clayton
  • 80,996
  • 26
  • 120
  • 129
  • hey if the block refers to local variables of some other function, will it be fine ? – Amogh Talpallikar Nov 19 '12 at 21:30
  • local variables are fine provided they're in scope where the block is defined - and you'll need to add a block storage type to them (e.g. __weak or __strong). If you access member variables of the class, the block will retain self so that'll be ok too. This can cause leaks though if you're not careful. – Ben Clayton Nov 19 '12 at 21:44
  • "and you'll need to add a block storage type to them" only if you need to assign to them – newacct Nov 20 '12 at 00:31