ARC中delegate为何不使用assign

I just ran into this problem and solved it. For ARC, the solution is to use the weak attribute instead of assign.

The crash come because the delegate

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.

As already mentioned, using a strong or assign attribute on a delegate (as many have mentioned) in ARC will result in a retain cycle. So don't do it, you don't need to.

assign “设置方法”只会招待针对“纯量类型”(scalar type,例如CGFloat或NSInteger等)的简单赋值操作。

strong 此特质表明该属性定义了一个拥有关系(owning relationship)。为这种属性设置新值时,设置方法会先保留新值,再释放旧值,然后再将新值设置上去。

weak 此特质表明该属性定义了一种非拥有关系(no owning relationship),为这种属性添加新值时,设置方法即不保留新值,也不保留旧值。此特质同assign类似,然而在改改所指的对象遭到摧毁时,属性值也会清空(nil out).

unsafe_unretained

看名字就知道了

不安全 不增加引用计数

NSString* str1 = @"123";

unsafe_unretianed NSString* str2 = str1;

[str1 release];

str2也跟着消失的无影无踪了,指针的地址空间都被清空了,和C++的引用很相似,别名

你可能感兴趣的:(delegate)