objective-c - 复制是否也转移保留计数?

标签 objective-c memory-management

假设我有一个对象,例如一个 NSString,其保留计数为 5。当我对其调用 copy 时,我得到了该对象的一个​​新副本;这个新对象是否具有其原始对象的保留计数?

最佳答案

这取决于。 copycopyWithZone: 的便捷方法, 和 "NSCopying Protocol Reference"状态:

Your options for implementing this protocol are as follows:

  • Implement NSCopying using alloc and init... in classes that don’t inherit copyWithZone:.
  • Implement NSCopying by invoking the superclass’s copyWithZone: when NSCopying behavior is inherited. If the superclass implementation might use the NSCopyObject 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/

相关文章:

memory-management - 页表具有有效无效位的目的是什么?

c++ - 如何使用 "new"而不是 malloc 分配内存?

iOS 在关闭 View Controller 后释放内存

ios 音频队列 - 如何测量缓冲区中的音频电平?

objective-c - 核心数据委托(delegate)保存模式

ios - 解析后端上传文件的新错误 - 错误 : File name must be a string - PFFile

iPhone UIViewController 进入状态栏

iphone - ios coredata 搜索大型数据集

c# - .net 内存使用情况,决定私有(private)字节大小的因素

php - 取消设置 PHP 脚本中的所有变量