gpt4 book ai didi

objective-c - NSString 长度和 retainCount。需要澄清

转载 作者:太空狗 更新时间:2023-10-30 04:00:32 25 4
gpt4 key购买 nike

基于以下代码,请指教

NSString *str= [[NSString alloc] initWithString:@"Hello world"];   

NSLog(@"Length: %lu\n", [str length]); // 11
NSLog(@"Retain count is %lu\n", [str retainCount]); //1152921504606846975

[str release];

NSLog(@"%lu\n", [str length]); // 11
NSLog(@"Retain count is %lu\n", [str retainCount]); //1152921504606846975
  1. 本来我想知道为什么数字这么大但是后来看到一个post explaining it .让我问这个......为什么无论我使用 %d 还是 %lu,这个数字都会有很大的变化。最初,我使用了 %d,但收到警告说“转换指定类型 int 但参数具有 NSUInteger 类型(又名 unsigned long)。解决方法是更改​​ % d%lu"

  2. 为什么保留计数不递减?发送strrelease

  3. 后,大数仍然显示不变
  4. 为什么在 release 发送后我仍然可以访问 str

最佳答案

这可能是一个难以接受的答案,但这是您应该做的:

  1. 别担心。(就 %d/%lu 而言,这些说明符只是期望不同的数据类型,而 %d (int) 的范围比 % 小得多且不同lu (unsigned long))
  2. 别担心。
  3. 不要这样做,尤其不要依赖它。

可能是因为你以一个常量字符串(@"Hello world")开始,当你调用 release 时内存没有被释放,并且 retainCount 很大。但是如果您必须关心 retainCount,那您就错了。

您在正确的位置释放了字符串,这才是最重要的——以后永远不要尝试使用它。

关于objective-c - NSString 长度和 retainCount。需要澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6727677/

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