如果我们在 objective c 中使用 MRC,sushiName 和 sushiString 的保留计数是多少。那么 _sushiTypes 呢?

If we use MRC in objective c what is the retain count of sushiName and sushiString . And what about _sushiTypes?

NSString * sushiName = [_sushiTypes objectAtIndex:indexPath.row]; 
NSString * sushiString = [NSString stringWithFormat:@"%d: %@", 
    indexPath.row, sushiName]; 

如果我们在 objective c 中使用 MRC,sushiNamesushiString 的保留计数是多少? 那么 _sushiTypes 呢?

回答您的问题:

  • objectAtIndex 的调用不会将所有权转移给您的代码(因此,实际上,保留计数没有改变)。如果要确保对象在从数组中删除时不会被释放(或者数组本身被释放),则需要使用 retain.

  • 声明所有权
  • sushiString 引用了 stringWithFormat 返回的自动释放对象,该对象尚未将所有权转让给您的代码。因此,如果您不想在自动释放池耗尽时释放它,您必须再次 retain 自己。

  • Re _sushiTypes,我们不能说,因为你没有分享你如何实例化 and/or 你可能正在做的任何事情来声明对该数组的所有权。


有关详细信息,请参阅 Advanced Memory Management: Basic Memory Management Rules:

The memory management model is based on object ownership. Any object may have one or more owners. As long as an object has at least one owner, it continues to exist. If an object has no owners, the runtime system destroys it automatically. To make sure it is clear when you own an object and when you do not, Cocoa sets the following policy:

  • You own any object you create

    You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).

  • You can take ownership of an object using retain

    A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. You use retain in two situations: (1) In the implementation of an accessor method or an init method, to take ownership of an object you want to store as a property value; and (2) To prevent an object from being invalidated as a side-effect of some other operation (as explained in Avoid Causing Deallocation of Objects You’re Using).

  • When you no longer need it, you must relinquish ownership of an object you own

    You relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.

  • You must not relinquish ownership of an object you do not own

    This is just corollary of the previous policy rules, stated explicitly.

一些最后的观察:

  1. 如果您担心 Objective-C MRC 世界中的内存管理,静态分析器(按 shift+命令+B 或从 "Product" 菜单中选择 "Analyze")非常擅长识别问题。在执行任何其他操作之前,请确保您的静态分析器的健康状况良好。

  2. NSString 具有各种内部性能增强功能,可能会使字符串看起来比您对基本内存管理规则(上文)所期望的要长。警惕从对 NSString 个对象的任何经验测试中得出更广泛的结论。它们的行为与其他对象不同。

  3. 我建议你不要考虑保留计数,而是考虑上面引用中提到的“所有权”。有关详细信息,请参阅 Advanced Memory Management Guide