Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to retain blocks in Objective-C for iOS?

I would like to make a method that takes in a block, saves it in a member, starts up an asynch task, and then calls the block when the asynchronous call makes its completion callback.

Do I have to retain the block? Are blocks memory managed the same way as any other object? Can I synthesize a property to hold the block?

like image 296
evilfred Avatar asked May 19 '11 23:05

evilfred


2 Answers

Blocks are similar to other objects for memory management, but not the same. When a block which accesses local variables is created, it is created on the stack. This means that it is only valid as long as its scope exists. To save this block for later, you must copy it, which copies it to the heap. Therefore, to protect against problems with such blocks, you should copy, not retain, your block before you store it in an instance variable.

like image 166
ughoavgfhw Avatar answered Nov 02 '22 00:11

ughoavgfhw


You'll have to copy the block, yes. Blocks are regular Objective-C objects.

like image 2
Dave DeLong Avatar answered Nov 01 '22 23:11

Dave DeLong