NSString cStringUsingEncoding return 值的寿命

Lifespan of NSString cStringUsingEncoding return value

我有一个 NSTextField 并像这样获取它的内容

NSString *s = [textField stringValue]

现在我想将此 NSString 转换为我的平台无关 C 代码可以处理的字符串。因此我在做:

const char *cstr = [s cStringUsingEncoding:NSISOLatin1StringEncoding];

我现在不明白的是这个"cstr"指针的有效期有多长。 cStringUsingEncoding 的 Apple 文档说:

The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current memory is emptied, whichever occurs first. You should copy the C string or use getCString:maxLength:encoding: if it needs to store the C string beyond this time.

关于这个的两个问题:

  1. 我想前面提到的 "receiver" 是 [textField stringValue] 返回的 NSString。因为我不拥有这个 NSString,我怎么知道它什么时候会被释放?假设在释放 NSTextField 小部件之前不会释放此 NSString 是否安全?

  2. "until the current memory is emptied"具体是什么意思?我完全不明白这个。

当然,我可以继续复制,但我想了解 cStringUsingEncoding 返回的字符串指针的有效期。

我知道这里有几个类似的问题,但是 none 真的可以回答我的问题,因为在我的例子中,NSString 的所有者是 NSTextField 小部件,我不知道这个小部件什么时候会发布NSString 或者它是否在小部件本身的整个生命周期内保持有效。

I suppose the aforementioned "receiver" is the NSString returned by the [textField stringValue]

是的,在这种情况下接收者是 s

Since I don't own this NSString how can I tell when this will be freed?

你不知道。您应该通过将 s 存储在实例变量中来保留它,只要您需要它

Is it safe to assume that this NSString won't be freed before the NSTextField widget will be freed?

不,因为您不知道文本字段 s 向您返回的内容或方式

What does "until the current memory is emptied" mean precisely? I don't understand this at all.

好问题。另外,很难说,因为您不拥有该字符串或不知道其底层实现。说这是一个可变的字符串,它被改变了,必须重新分配内存...

如果你 copy s,你可以非常确定你的安全,将副本存储在实例变量中,然后使用副本获取 C 字符串(或者只复制 C 字符串).

Receiver 肯定意味着字符串 s,当 s 被释放时,对 cstr 的危险是显而易见的。我认为短语 "or until current memory is emptied" 是 ARC 引入的文档错误。可以读作"or until an ARC-implied release is executed".

参见 2010 年的文档 quoted here 作为证据。我认为作者可能正在搜索 'autorelease pool' 来更新文档,正在寻找 "or until the current autorelease pool is emptied" 的一个无害的、ARC 兼容的同义词。我认为放弃析取会更好。

无论如何,要么控制 NSString,要么复制 cstring。