我是否必须在Objective-C中为iOS保留块?

时间:2022-09-06 21:16:02

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?

我必须保留该块吗?块内存的管理方式与其他任何对象相同吗?我可以合成一个属性来保存块吗?

2 个解决方案

#1


36  

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


2  

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

你必须复制块,是的。块是常规的Objective-C对象。

#1


36  

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


2  

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

你必须复制块,是的。块是常规的Objective-C对象。