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.
You can by moving the blocks into heap by using
Block_copyfunction on the block when you store it in your array andBlock_releasewhen you are done with it.Block_copywill 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.
When you want to add a block to the array you can copy the block like this:
When you are done with the block you need to release it like this (not necessary with ARC):