ios:保留2147483647的计数?

发布于 2024-11-28 11:49:21 字数 794 浏览 2 评论 0原文

可能的重复:
NSString keepCount 为 2147483647
Objective C NSString* 属性保留计数奇数

看一下以下内容代码:

NSString* testString = [[NSString alloc] initWithString:@"Test"];
NSLog(@"[testString retainCount] = %d", [testString retainCount] );
NSMutableArray* ma = [[NSMutableArray alloc] init];
[ma insertObject:testString atIndex:0];
[testString release];
NSLog(@"%@", [ma objectAtIndex:0]);

这是控制台上的输出:

[testString retainCount] = 2147483647
Test

这是怎么发生的?我期望的是 1 而不是 2147483647!

Possible Duplicates:
NSString retainCount is 2147483647
Objective C NSString* property retain count oddity

Have a look at the following code:

NSString* testString = [[NSString alloc] initWithString:@"Test"];
NSLog(@"[testString retainCount] = %d", [testString retainCount] );
NSMutableArray* ma = [[NSMutableArray alloc] init];
[ma insertObject:testString atIndex:0];
[testString release];
NSLog(@"%@", [ma objectAtIndex:0]);

This is the output on the console :

[testString retainCount] = 2147483647
Test

How can this happen? I expected 1 not 2147483647!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野心澎湃 2024-12-05 11:49:21

您使用字符串文字启动您的 NSString 对象,并发生以下 2 件事:

  1. 由于 NSString 是不可变的 -initWithString: 方法优化字符串创建,以便您的 testString 实际上指向您使用 (@"Test ")
  2. @"Test" 是一个字符串文字,它在编译时创建并存在于特定的地址空间中 - 您无法释放它,释放和保留不会影响其保留计数,并且它始终INT_MAX

综上所述,您仍然应该遵循内存管理规则使用您的字符串对象(当您使用 alloc/init 创建它时,您应该释放它)并且您会没事的

You initiate your NSString object with string literal and 2 following things happen:

  1. As NSString is immutable -initWithString: method optimizes string creation so that your testString actually points to a same string you create it with (@"Test")
  2. @"Test" is a string literal and it is created in compile time and lives in a specific address space - you cannot dealloc it, release and retain does not affect its retain count and it is always INT_MAX

With all mentioned above you still should work with your string object following memory management rules (as you created it with alloc/init you should release it) and you'll be fine

め七分饶幸 2024-12-05 11:49:21

对于retainCount的结果你只能有两个期望:

1)它大于1。你无法预测它实际上是什么数字,因为你不知道还有谁在使用它。你不知道别人如何使用它。这不是你应该关心的数字。

2)人们会告诉你不要使用它。因为你不应该。使用规则来平衡保留和释放。不要使用保留计数。它会让你感到沮丧和困惑,毫无价值。

You can only have two expectations for the result of retainCount:

1) It's greater than 1. You cannot predict what number it will actually be because you don't know who else is using it. You don't know how somebody else is using it. It's not a number you should care about.

2) People will tell you not to use it. Because you shouldn't. Use the rules to balance your retains and releases. Do not use retainCount. It will frustrate and confuse you, for no value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文