tags:

views:

324

answers:

4

Hello Friends,

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,

+10  A: 

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

Vladimir
`initWithString:` cannot assign anything to its caller's variables. It can, however, be implemented to simply return the string it was passed when copying the string would provide no benefit.
Peter Hosey
@Peter, you're absolutely right. I corrected the answer (hope my English is not letting me down again here :( )
Vladimir
Yup, the amended version is correct.
Peter Hosey
A: 

Your value is UINT_MAX=0x7FFFFFFF

You might override this method in a class to implement your own reference-counting scheme. For objects that never get released (that is, their release method does nothing), this method should return UINT_MAX, as defined in limits.h.

It is static string, then object can not be dealloc.

Benoît
Isn't it INT_MAX?
BoltClock
Yes, thx... but then, the apple doc is not good ?
Benoît
A: 

constants and literals have retain count = INT_MAX, they can't be released as they are allocated separately not on heap with other objects (afaik)

Agito
+16  A: 

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.

bbum
Just to clarify for people new to this, `autorelease` also counts as a call to `release`.
Dad