请解释以下keywords的区别: assign vs weak, __block vs __weak

assign vs weak, __block vs __weak

字数364 阅读74 评论0

在objective-c中,类中的全局变量经常使用如下的方式申明。

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

其中的1,2处是对此变量的一些属性申明。有以下几种
strong
weak
assign
strong 和 weak 是在arc后引入的关键字,strong类似于retain,引用时候会引用计算+1,weak相反,不会改变引用计数。
weak和assign都是引用计算不变,两个的差别在于,weak用于object type,就是指针类型,而assign用于简单的数据类型,如int BOOL 等。
assign看起来跟weak一样,其实不能混用的,assign的变量在释放后并不设置为nil(和weak不同),当你再去引用时候就会发生错误,崩溃,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));

 
posted @ 2015-11-02 17:11  锄,禾日当午  阅读(329)  评论(0编辑  收藏  举报