我是否必须在 iOS 的 Objective-C 中保留块?
我想创建一个方法,它接受一个块,将其保存在成员中,启动异步任务,然后在异步调用进行完成回调时调用该块。
我必须保留该块吗?块内存的管理方式是否与任何其他对象相同?我可以合成一个属性来持有该方块吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
块与内存管理的其他对象类似,但又不相同。当创建访问局部变量的块时,它会在堆栈上创建。这意味着它仅在其范围存在时才有效。要保存此块供以后使用,您必须
复制
它,这会将其复制到堆中。因此,为了防止此类块出现问题,您应该在将块存储到实例变量中之前复制而不是保留该块。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.是的,您必须复制该块。块是常规的 Objective-C 对象。
You'll have to copy the block, yes. Blocks are regular Objective-C objects.