ios:保留2147483647的计数?
可能的重复:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用字符串文字启动您的 NSString 对象,并发生以下 2 件事:
综上所述,您仍然应该遵循内存管理规则使用您的字符串对象(当您使用 alloc/init 创建它时,您应该释放它)并且您会没事的
You initiate your NSString object with string literal and 2 following things happen:
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
对于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.