gpt4 book ai didi

objective-c - NSString cStringUsingEncoding 返回值的生命周期

转载 作者:行者123 更新时间:2023-12-03 17:10:55 24 4
gpt4 key购买 nike

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

NSString *s = [textField stringValue]

现在我想将此 NSString 转换为我的独立于平台的 C 代码可以处理的字符串。因此我正在这样做:

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

我现在不明白的是这个“cstr”指针保持有效多久。 Apple 文档中关于 cStringUsingEncoding 的说明是:

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. 我想前面提到的“接收者”是[textField stringValue]返回的NSString。既然我不拥有这个 NSString,我怎么知道它什么时候会被释放呢?可以安全地假设在释放 NSTextField 小部件之前不会释放此 NSString 吗?

  2. “直到当前内存清空”到底是什么意思?我完全不明白这个。

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

我知道这里有几个类似的问题,但没有人能真正回答我的问题,因为就我而言, 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.

好问题。另外,很难说,因为您不拥有该字符串或不了解其底层实现。说它是一个可变字符串,已发生变异并且必须重新分配内存......

如果您复制 s,将副本存储在实例变量中,然后使用副本获取 C 字符串(或者只是复制 C 字符串)。

关于objective-c - NSString cStringUsingEncoding 返回值的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com