環境:block函數內 先寫結論: 在MRC下,咱們一般使用__block,而在ARC下咱們一般使用__weak, 或者__unsafe_unretaine __block(不安全,不建議使用) 來修飾對象防止循環引用而形成的內存泄露。 注意: __weak 自己是能夠避免循環引用的問題的,可是其會致使外部對象釋放了以後,block 內部也訪問不到這個對象的問題,咱們能夠經過在 block 內部聲明一個 __strong 的變量來指向 weakObj,使外部對象既能在 block 內部保持住,又能避免循環引用的問題 __block 自己沒法避免循環引用的問題,可是咱們能夠經過在 block 內部手動把 blockObj 賦值爲 nil 的方式來避免循環引用的問題。另一點就是 __block 修飾的變量在 block 內外都是惟一的,要注意這個特性可能帶來的隱患。 在MRC中, __block經過用在修改局部變量數據,使變量數據生效,變量會在內存中強引用。 __block關鍵字能夠知足block內修改block外變量的需求,__weak能夠解決循環引用的問題 問題:__block也能夠解決循環引用的問題? 爲何會說block也能夠起到和weak同樣的做用呢? 之前在非arc環境中,__block修飾的變量在Block copy時是不會retain的,因此,也能夠作到破解循環引用。 因此說是指在非ARC環境中__block能夠解決循環引用問題
http://www.devdiv.com/ios_weak_block_-blog-70053-56933.html html
http://blog.sina.com.cn/s/blog_cf6377e70102vhq8.htmlios
官方解釋:From the docs about __block安全
__block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created w函數
So they are technically different things. __block is to stop your variable being copied from your external scope into your block scope. __weak is a self delimiting weak pointer.spa
From the docs about __weakcode
__weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.orm
中文意思,請你們自行理解,咱們來看你們的解釋,縱觀國內技術文章,基本都是一說一大片,發現真正沒有解決以前的疑問,有什麼不一樣,好了,先看下面的這段話:htm
So they are technically different things. __block is to stop your variable being copied from your external scope into your block scope. __weak is a self delimiting weak pointer.對象
Note I said technically, because for your case they will do (almost) the same thing. The only difference is if you are using ARC or not. If your project uses ARC and is only for iOS4.3 and above, use __weak. It ensures the reference is set to nil if the global scope reference is releases somehow. If your project doesn't use ARC or is for older OS versions, use __block.blog
There is a subtle difference here, make sure you understand it.
EDIT: Another piece to the puzzle is __unsafe_unretained. This modifier is almost the same as __weak but for pre 4.3 runtime environments. HOWEVER, it is not set to nil and can leave you with hanging pointers.
總結以下:
AIn manual reference counting mode, __block id x; has the effect of not retaining x. In ARC mode, __block id x; defaults to retaining x (just like all other values). To get the manual reference counting mode behavior under ARC, you could use __unsafe_unretained __block id x;. As the name __unsafe_unretained implies, however, having a non-retained variable is dangerous (because it can dangle) and is therefore discouraged. Two better options are to either use __weak (if you don’t need to support iOS 4 or OS X v10.6), or set the __block value to nil to break the retain cycle.
也就說,在MRC下,咱們一般使用__block ,而在ARC下咱們一般使用__weak , 或者__unsafe_unretaine __block(不安全,不建議使用) 來修飾對象防止循環引用而形成的內存泄露。