"The assign keyword will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates."
The reason that you avoid retaining delegates is that you need to avoid a retain loop:
A creates B A sets itself as B's delegate … A is released by its owner
If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.
The reason that you avoid retaining delegates is that you need to avoid a retain loop:
A creates B A sets itself as B's delegate … A is released by its owner
If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.
You shouldn't worry about A going away b/c it owns B and thus gets rid of it in dealloc.
Copy其实是建立了一个相同的对象,而retain不是:
比如一个NSString对象,地址为0×1111,内容为@”STR”
Copy到另外一个NSString之后,地址为0×2222,内容相同,新的对象retain为1,旧有对象没有变化
retain到另外一个NSString之后,地址相同(建立一个指针,指针拷贝),内容当然相同,这个对象的retain值+1
也就是说,retain是指针拷贝,copy是内容拷贝。
本文探讨了Objective-C中assign、retain及copy关键字的区别及其应用场景。详细解释了为何delegate通常使用weak引用以避免内存泄露,并对比了retain与copy在字符串对象处理上的不同。

1378

被折叠的 条评论
为什么被折叠?



