我是否必须在Objective-C中为iOS保留块? [英] Do I have to retain blocks in Objective-C for iOS?

查看:83
本文介绍了我是否必须在Objective-C中为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?

推荐答案

块与内存管理的其他对象类似,但不一样。当创建访问局部变量的块时,它将在堆栈上创建。这意味着只有在其范围存在的情况下它才有效。要保存此块以供日后使用,必须复制它,将其复制到堆中。因此,为了防止出现此类块的问题,您应该在将块存储到实例变量中之前复制而不是保留块。

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中为iOS保留块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆