为什么 block property 要用 copy 修饰?

2017-09-06  本文已影响31人  RYANIM

https://stackoverflow.com/questions/27152580/cocoa-blocks-as-strong-pointers-vs-copy/27156860#27156860
最近遇到一个问题,「为什么 block 要用 copy 修饰」?

首先 block 是一个 OC 对象 「Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. 」

之前知道 在 ARC 中 block 使用 strong 或者 copy 是一致的,出于历史习惯会偏向于继续使用 copy. 那现在的问题就是为什么历史上要用 copy 呢?

Note: You should specify copy as the property attribute, because a block needs to be copied to keep track of its captured state outside of the original scope. This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically, but it’s best practice for the property attribute to show the resultant behavior.

You only need to make a copy when you expect the block to be used after destruction of the scope within which it was declared. Copying moves a block to the heap.

Block 不同于其他的对象,它能存在于栈中,特别是创建的时候就是在创建在栈上。类似局部变量,存在于栈上,当运行出了作用域之后,栈上的变量就被销毁了。所以 block 在栈上创建之后就被销毁了。

为此要把 block 复制到堆上,使用 block_copy()(也可以用 [block copy] 代替)。

上一篇下一篇

猜你喜欢

热点阅读