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

可紊 提交于 2019-12-04 09:14:20

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/6065963/do-i-have-to-retain-blocks-in-objective-c-for-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!