itsaboutcode
itsaboutcode

Reputation: 25099

NSString retain Count

Just couple of days i was working on a project and i have to see what is retain count of a string.

But it always return me "2147483647", Why it is so?

Check out this code to check it yourself.

NSString *str = [[NSString alloc] initWithString:@"Hello World"];
NSLog(@"String Retain Count: %i", [str retainCount]); 

So my question is why it is not returning 1 like other objects return, why i am getting "2147483647"

Thanks in advance.

Upvotes: 7

Views: 6493

Answers (3)

Dave DeLong
Dave DeLong

Reputation: 243156

The compiler is smarter than you.

It sees @"Hello world" and thinks "Aha! A constant string!"

It then sees [[NSString alloc] initWithString:@"Hello world!"] and thinks "Aha! An immutable object created with a constant string!"

It then collapses both of them down into a single NSConstantString, which has a retainCount of UINT_MAX, so that it can never be released.

Upvotes: 27

mahboudz
mahboudz

Reputation: 39376

NSString *str = [[NSString alloc] initXXX 

usually would allocate some RAM and return you a pointer. This RAM would then be subject to releases and reatins. However, when you do:

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

the string returned is @"Hello World", which is already allocated because it was a string literal. Since it is a string literal, there is no way to release it, and thus the system has to mark it as unreleasable. The way it does that is to set its retain count to the max integer value.

NString  *str = [[NSString alloc] initWithFormat:@"Hello World. Today is @%", todayDate];

This string will have a retainCount of 1. Although there is a string constant in there, it is appended to by another string. Since you can't modify that constant string, a copy of the "Hello World. " string is made, and the content of the todayDate string is added to that. That memory now is given ownership to the caller, with a retainCount of 1.

Upvotes: 4

Tim
Tim

Reputation: 60130

The string is being optimized at compile-time to a statically allocated instance of NSString in order to save on some variable overhead and the like. You're seeing such a high retain count because static strings have a retain count of the maximum integer on whatever platform you're developing on.

Upvotes: 2

Related Questions