assign vs weak, __block vs __weak

在objective-c中,類中的全局變量經(jīng)常使用如下的方式申明。

@property(nonatomic(1),strong(2))UIImageView *imageView;

其中的1,2處是對此變量的一些屬性申明。有以下幾種
*strong *
weak
assign
strong 和 weak 是在arc后引入的關鍵字,strong類似于retain,引用時候會引用計算+1,weak相反,不會改變引用計數(shù)。
weak和assign都是引用計算不變,兩個的差別在于,weak用于object type,就是指針類型,而assign用于簡單的數(shù)據(jù)類型,如int BOOL 等。
assign看起來跟weak一樣,其實不能混用的,assign的變量在釋放后并不設置為nil(和weak不同),當你再去引用時候就會發(fā)生錯誤,崩潰,EXC_BAD_ACCESS.

Has an assign attribute, AND Has been deallocated. Thus when you attempt to call the respondsToSelector method on delegate, you get a EXC_BAD_ACCESS. This is because objects that use the assign property will not be set to nil when they are deallocated. (Hence why doing a !self.delegate before the respondsToSelector does not prevent the responseToSelector from being called on a deallocated object, and still crashes your code) The solution is to use the weak attribute, because when the object deallocates, the pointer WILL be set the nil . So when your code calls respondsToSelector on a nil, Objective C will ignore the call, and not crash.

block 不能修改局部變量,如果需要修改需要加上__block.
block 會對對象強引用,引起retain-cycle,需要使用__weak

__weak __typeof(&*self)weakSelf =self;

在block種使用weakSelf可避免這種強引用。
(兩個指針,指向同一塊地址(self));

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容