objective-c - NSString 中的 stringWithString 和 initWithString 中的对象所有权

标签 objective-c cocoa

我知道任何 init... 方法都会初始化一个新对象,而 NSString stringWithString 会将参数字符串复制为一个新对象。我也明白,作为对象的所有者,我可以控制我分配的任何对象的释放/解除分配。我不明白的是我什么时候会使用 stringWithString 方法,因为以这种方式分配的任何局部变量都会让 NSString 而不是本地类“拥有”它的内存。

Kochan 的“Programming in Objective C”一书(第 1 版)使用以下代码(参见第 342-344 页)来解释 initWithString 优于 stringWithString,因为 AddressCard 类将拥有名称变量内容。此外,使用 stringWithString 方法重复调用 setName 版本时,我没有收到任何错误。 TIA!!

//header file has appropriate declarations but not included here:
#import "AddressCard.h"

@implementation AddressCard;

-(NSString *) name
{
   return name;
}

//Recommended code:
-(void) setName: (NSString *) theName
{
   [name release]
   name = [[NSString alloc] initWthString: theName];
}

//Incorrect code according to Kochan:
-(void) setName: (NSString *) theName
{
   [name release]
   name = [NSString stringWthString: theName];
}

//rest of class implementation code snipped
@end

最佳答案

What I don't understand is when would I use the stringWithString method since any local variable assigned that way would have it's memory "owned" by NSString instead of the local class.

什么?没有。

规则很简单:

  • alloccopycopyWithZonenew 返回的任何对象的保留计数为 1。
  • retain 增加接收对象的保留计数。
  • release 减少接收对象的保留计数。
  • autorelease 告诉当前的自动释放池“稍后”向接收对象发送 release 消息。
  • 任何名称中没有“new”或“copy”的工厂方法(例如,stringWithString:)都会返回一个它代表您自动释放的对象。

或者,稍微消化一下:

  • 任何名称包含 copyallocretainnew 的方法都会返回您拥有的对象.
  • 任何不属于您的方法都会返回您不拥有的对象。
  • 要拥有一个对象,请保留它。

您显示的 setName: 的不正确实现是不正确的,因为当您打算拥有该对象时,它将自动释放的对象存储在实例变量中。您应该保留它,或者在这种情况下复制它。一种方法是简单地使用 allocinitWithString:,就像您展示的正确示例一样;另一种方式是复制

The Memory Management Programming Guide for Cocoa explains everything.每个 Cocoa 或 Cocoa Touch 程序员都应该不时阅读或重新阅读它。

关于objective-c - NSString 中的 stringWithString 和 initWithString 中的对象所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/318666/

相关文章:

macos - Mac OS 如何确定要使用哪个 localization.strings 文件?

iphone - UITextchecker用哪种语言进行拼写检查?

ios - 如何自定义 FSCalendar

objective-c - 在 cocoa 屏幕上观察全局鼠标位置?

objective-c - NSDictionary 到 NSArray?

iphone - performSelectorOnMainThread 嵌入在 didUpdateToLocation

cocoa - 如何限制 NSTokenField 中的 token 数量?

objective-c - 是否可以从另一个 UIViewController 的 uiview 加载 UIVIewcontroller

Cocoa:将操作(复制:、粘贴:等)转发到响应者链

ios - 将数据存储在自定义类中的 NSArray 中并在其他类/ Controller 中使用