I want to print retain count of NSString
in AppDelegate
class in didFinishLaunchingWithOptions
method
NSString *str = [[N
Apple docs say:
Special Considerations
This method is of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.
So you shouldn't count on its correctness.
Also, -1
is actually largest unsigned integer, not negative value. Retain count returns NSUInteger
, so you should use %u
instead of %d
.
Generally you should no longer use the -retainCount
method, as pointed out by others' answers. The reason is, a lot of retain/release work is done inside the NSString
class depending on how you create it. When you create an NSString
you could actually be creating one of many NSString
subclasses (the id
return type of the initialisers is not specific).
All NSConstantStrings
(those created by @""
) are not releasable - they exist for the duration of the program (as specified by both gcc and clang). Thus, Apple have arbitrarily set its retainCount
to be the highest possible unsigned integer (or -1 if it is read as signed, as it is here) because it makes no sense for a constant object, alive for the duration of the program, to have a retain count.
When you create an empty string in the way you have, it is likely Apple just automatically point you to the constant @""
in memory as it takes up less space at runtime. As your object is now an NSConstantString
, it is implemented to return a retain count of -1.
EDIT: Incidentally, as NSConstantString
is a subclass of NSString
it must implement the methods that NSString
implements, including -retainCount
. This is why you can actually call the -retainCount
method on a constant string object (and why Apple make it return a special value). This inheritance relationship can be found near the bottom of the NSString.h
header.
NSUIntegerMax
means the returned object is immortal. This used to be in the docs, but has since been removed (because -retainCount
is very discouraged).
In MRC, some people would actually override -retainCount
to prevent their singletons from ever being deallocated.
In this case, it is a logical optimization for [[NSString alloc] init]
to return a constant/immortal, rather than creating an empty string for each request. Of course, you should not rely on this detail/behavior in your program.