在 Objective-C 中对 Block 应用 property 时的注意事项
?
應(yīng)當(dāng)使用:@property (nonatomic, copy)
今天在這個(gè)問(wèn)題上犯錯(cuò)誤了,找了好久才知道原因。
另外,簡(jiǎn)單的進(jìn)行反匯編看了下,Block 被存儲(chǔ)在靜態(tài)變量區(qū),運(yùn)行時(shí)構(gòu)造出一個(gè)運(yùn)行棧,進(jìn)行調(diào)用。
retain 并不會(huì)改變 Block 的引用計(jì)數(shù),因此對(duì) Block 應(yīng)用 retain 相當(dāng)于 assign。
但是既然在靜態(tài)存儲(chǔ)區(qū),為什么會(huì)出現(xiàn) EXC_BAD_ACCESS 呢?代碼都在的呀。
網(wǎng)上都說(shuō) Block 在棧上,這應(yīng)該是錯(cuò)誤的:指向 Block 代碼的指針在棧上。
我感覺(jué)原因是這樣:
執(zhí)行靜態(tài)區(qū)的代碼,需要特殊的構(gòu)造,比如:加載到寄存器,調(diào)整好 ESP 等。
而堆上的代碼可以直接執(zhí)行。
期待更詳細(xì)的解釋。
When storing blocks in properties, arrays or other data structures, there’s an important difference between using?copy?or?retain. And in short, you should always use?copy.
When blocks are first created, they are allocated on the stack. If the block is called when that stack frame has disappeared, it can have disastrous consequences, usually a EXC_BAD_ACCESS or something plain weird.
If you?retain?a stack allocated block (as they all start out being), nothing happens. It continues to be stack allocated and will crash your app when called. However, if you?copy?a stack allocated block, it will copy it to the heap, retaining references to local and instance variables used in the block, and calling it will behave as expected. However, if you?copy?a heap allocated block, it doesn’t copy it again, it just?retains?it.
So you should always declare your blocks as properties like this:
@property (copy, ...) (int)(^aBlock)();And never like this:
@property (retain, ...) (int)(^aBlock)();And when providing blocks to?NSMutableArrays and the like, always?copy, never?retain.
轉(zhuǎn)載于:https://www.cnblogs.com/Proteas/archive/2012/06/26/2563747.html
總結(jié)
以上是生活随笔為你收集整理的在 Objective-C 中对 Block 应用 property 时的注意事项的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: js触发asp.net的Button的O
- 下一篇: 【英语天天读】Man's Youth