objective-c - ObjC 书籍和官方文档中内存管理描述之间的冲突

标签 objective-c cocoa memory-management

我正在努力学习/理解在使用或创建各种对象时会发生什么以及为什么。 (希望从文档中学习。)

我正在阅读“Programming in Objective-C 2.0”(第 2 版,Steven Kochan 着)。在第 408 页,第一段是对保留计数的讨论:

Note that its reference count then goes to 2. The addObject: method does this automatically; if you check your documentation for the addObject: method, you will see this fact described there.

所以我阅读了 addObject: 文档:

Inserts a given object at the end of the array.

那里,缺少描述,而其他项目,如 arrayByAddingObject:state it:

Returns a new array that is a copy of the receiving array with a given object added to the end.

在引用文献中的什么地方指出 addObject: 增加了保留计数?鉴于 ARC 的存在,我仍然应该了解这些方法在做什么以避免错误和问题。 ARC为此带来了什么? (打算再读一遍……)

最佳答案

好问题,我很高兴看到有人真正阅读文档并试图理解它们!

由于您正在寻找如何使用 Apple 的文档研究答案而不是实际答案本身,因此我是这样找到答案的:

  • 首先我查看了 addObject: 的类引用,它是 NSMutableArray 的一个方法,没有提到内存管理。
  • 然后我查看顶部的概述部分...嗯,还是不走运。
  • 由于行为可能是从父类继承的,所以我查看了类引用顶部的Inherits from 部分,发现NSArray 是最直接的 parent 。让我们检查一下:
  • Overview下有一小部分是关于retain的:

Special Considerations

In most cases your custom NSArray class should conform to Cocoa’s object-ownership conventions. Thus you must send retain to each object that you add to your collection and release to each object that you remove from the collection. Of course, if the reason for subclassing NSArray is to implement object-retention behavior different from the norm (for example, a non-retaining array), then you can ignore this requirement.

  • 好吧,我还是不开心……下一步呢? NSArray 的父类是 NSObject 并且我知道在这种情况下(根据经验)它不会被覆盖,所以我不会费心去检查它。 (如果父类是另一个类或可能被 NSObject 覆盖的东西,我会继续向上移动直到找到东西。)
  • Companion Guides 通常包含很多关于这些类型类(class)的有用信息。让我们试试第一个,集合编程主题
  • 第一部分(在概述之后)是访问索引和轻松枚举元素:数组。听起来很有希望!点击相关章节:“Arrays: Ordered Collections”
  • Array Fundamentals 下,还有指向更多信息的链接:

And when you add an object to an NSMutableArray object, the object isn’t copied, (unless you pass YES as the argument to initWithArray:copyItems:). Rather, an object is added directly to an array. In a managed memory environment, an object receives a retain message when it’s added; in a garbage collected environment, it is strongly referenced. When an array is deallocated in a managed memory environment, each element is sent a release message. For more information on copying and memory management, see “Copying Collections.”

关于objective-c - ObjC 书籍和官方文档中内存管理描述之间的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10768911/

相关文章:

iphone - 如何调试 iPhone 应用程序

ios - 应用程序未运行时不会收到远程通知

cocoa - 是否有适用于 Mac 桌面的 UIImagePicker

macos - NSScrollView 中的自定义 View 在滚动时乱写乱画

c++ - 如何在函数内返回值后删除指针

c - 如何在不释放内容的情况下释放指针?辅助变量

ios - C 回调中的 ARC 弱引用

ios - SceneKit 中的反重力物理

cocoa - NSScrollview 内的 NSView 不会改变大小

docker - 如何在docker上的cassandra中设置堆内存