NSString的长度和keepCount.需要澄清 [英] NSString length and retainCount. Clarification needed

查看:58
本文介绍了NSString的长度和keepCount.需要澄清的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据以下代码,请告知

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. 最初,我想知道为什么这个数字这么大,但随后看到了帖子对此进行了解释.让我问这个问题...为什么无论我使用%d还是%lu,这个数字都会有很大的变化.最初,我使用%d,但得到警告说"转换将类型指定为int,但参数的类型为NSUInteger(又名unsigned long).解决方法是将%d更改为%lu""

  1. Originally I was wondering why the number was so large but then saw a a post explaining it. Let me ask this instead ... Why does this number change greatly whether i use %d vs %lu. Originally, i used %d, but got a warning saying that "Conversion specified type int but the argument has the type NSUInteger (aka unsigned long). A fix was to change %d to %lu"

为什么保留计数不减少?发送release

Why doesn't the retain count decrement? Large number still shows up unchanged, after the str is sent release

在发送release后,为什么我仍然可以访问str?

Why am i still able to access the str, after it was sent release?

推荐答案

这可能很难接受,但这是您应该做的:

This may be a hard answer to accept, but it's what you should do:

  1. 不用担心.(就%d/%lu而言,这些说明符仅期望使用不同的数据类型,而%d(int)的范围要小得多,且与%的范围也不同lu(无符号长))
  2. 不用担心.
  3. 不要这样做,尤其不要依赖它.
  1. Don't worry about it. (in terms of %d/%lu, those specifiers simply expect different data types, and %d (int) has a much smaller and different range from %lu (unsigned long))
  2. Don't worry about it.
  3. Don't do it, and especially don't rely on it.

可能是因为您以常量字符串(@"Hello world")开头,所以在调用release时未释放内存,而keepCount大.但是如果您必须关心keepCount,那就错了.

It may be because you started with a constant string (@"Hello world") that the memory isn't being deallocated when you call release, and the retainCount is large. But if you have to care about the retainCount, you're doing it wrong.

您在正确的位置释放了字符串,这很重要-以后不要尝试使用它.

You are releasing the string in the right place, and that's what matters — don't ever try to use it later.

这篇关于NSString的长度和keepCount.需要澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆