假设我有一个对象,例如一个 NSString,其保留计数为 5。当我对其调用 copy 时,我得到了该对象的一个新副本;这个新对象是否具有其原始对象的保留计数?
最佳答案
这取决于。 copy
是 copyWithZone:
的便捷方法,
和 "NSCopying Protocol Reference"状态:
Your options for implementing this protocol are as follows:
- Implement
NSCopying
usingalloc
andinit...
in classes that don’t inherit copyWithZone:.- Implement
NSCopying
by invoking the superclass’scopyWithZone:
whenNSCopying
behavior is inherited. If the superclass implementation might use theNSCopyObject
function, make explicit assignments to pointer instance variables for retained objects.- Implement
NSCopying
by retaining the original instead of creating a new copy when the class and its contents are immutable.
(在收到所有反馈后,我修改了以下两个语句。) 子>
例如,NSString
是一个不可变对象,copy
只保留对象
并返回指向同一对象的指针。保留对象可能会增加
保留计数,但不一定(如字符串文字的情况。)
正在复制 NSMutableString
可能会创建一个新对象并返回它。
新对象将拥有独立于原始对象的保留计数。
但是你不应该关心其中的区别。使用手动引用计数,
copy
返回一个您拥有并且最终必须释放的对象。
使用 ARC,编译器会自动处理。
关于objective-c - 复制是否也转移保留计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18860273/