开发者

ios: Retain count of 2147483647? [duplicate]

开发者 https://www.devze.com 2023-03-26 18:05 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: NSString retainCount is 2147483647
This question already has answers here: Closed 11 years ago.

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 r开发者_如何学JAVAetainCount] = %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!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消