日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

在 Objective-C 中对 Block 应用 property 时的注意事项

發(fā)布時(shí)間:2025/3/15 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在 Objective-C 中对 Block 应用 property 时的注意事项 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

?

應(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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。