The method retainCount
is supposed to return an unsigned integer.
Why then, does [@"Hi" retainCount]
return -1?
The method retainCount
is supposed to return an unsigned integer.
Why then, does [@"Hi" retainCount]
return -1?
The simple answer is that because @"Hi
" is a string literal, it will always be sitting around in the binary executable image, and will never "go away", thus retain/release have no effect, and you're seeing UINT_MAX
(which looks like -1 when printed out signed eg with %d). (See Pete Kirkham's answer about NSObjects having these semantics).
Beyond this, it's useful to know that although @"Hi" behaves like an NSString*
, it's actually a compiler-created instance of the class CFConstantString
(or possibly NSConstantString, my debugger doesn't agree with some documentation), which wraps the literal string data and gives you the NSString* interface on it. But the compiler knows that these strings are special and can't ever get cleaned up, so they will always have a retainCount of UINT_MAX (-1)
According to Apple's NSObject documentation, it should return UINT_MAX
for objects which never get released. If you print UINT_MAX
as a signed int, you typically get -1
, which may be what you're doing - how are you outputting the value?
%zu
instead. –
Swoon Don't ever rely on the retainCount
method. Cocoa makes all sorts of optimisations behind-the-scenes which makes the retainCount
method unreliable and useless. Even Apple discourages using it. Stick to the memory management rules set out for Cocoa and you'll never need to know the retainCount
of any object.
The only difference between signed and unsigned integers is how you interpret the value. If read -1 as an unsigned int you'll find that it is the maximum value for an unsigned int.
For example: NSLog(@"%u", [@"Hello" retainCount]);
The reason it's such a large value is because constant string objects are never deallocated.
@"Hello" is not required to release with code ,
just be care for the object was create by "alloc" other no memory leak issue
© 2022 - 2024 — McMap. All rights reserved.
retainCount
is never useful to inspect yourself. – Gooseherd