Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain count after creating NSString

Tags:

iphone

I am creating a object which is type of NSString by the below method

NSString *str = [[NSString alloc] initWithString:@"aaaaaaaaaaaaaaa"];
    NSLog(@"retain count == %d",[str retainCount]);

after that i just printing the retain count value which is

2010-10-29 17:04:03.939 Example [1580:207] retain count == 2147483647

can any one answer this why here log is printing such garbage value

Thanks,

like image 278
AlexanderDeep Avatar asked Mar 21 '26 18:03

AlexanderDeep


2 Answers

Do not use -retainCount.

The absolute retain count of an object is meaningless.

You should call release exactly same number of times that you caused the object to be retained. No less (unless you like leaks) and, certainly, no more (unless you like crashes).

See the Memory Management Guidelines for full details.


In this specific case, you caused one retain with the call to alloc and, thus, you need to call release (or autorelease) once somewhere, anywhere, in your code.

like image 118
bbum Avatar answered Mar 24 '26 10:03

bbum


You're creating an immutable NSString object from a string literal. String literals are created at compile time and live for the whole run-time of your program - so it cannot be deallocated and retain/release has no effect on it. For optimization (as your NSString is immutable anyway) -initWithString: method can just return the string passed to it and so that string literal address becomes assigned to your str variable.

If you change your initialization code to -initWithFormat: then I suppose you'll get expected retain count value

like image 36
Vladimir Avatar answered Mar 24 '26 11:03

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!