Why does sending retainCount to @"Hi" return -1?
Asked Answered
F

5

2

The method retainCount is supposed to return an unsigned integer.

Why then, does [@"Hi" retainCount] return -1?

Fluoresce answered 6/1, 2010 at 17:1 Comment(1)
/me facepalms. retainCount is never useful to inspect yourself.Gooseherd
A
10

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)

Amain answered 6/1, 2010 at 17:16 Comment(0)
S
6

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?

Swoon answered 6/1, 2010 at 17:10 Comment(1)
That's for signed integers. Use %zu instead.Swoon
E
3

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.

Epenthesis answered 6/1, 2010 at 20:19 Comment(0)
A
0

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.

Articulator answered 6/1, 2010 at 17:19 Comment(0)
J
0

@"Hello" is not required to release with code ,

just be care for the object was create by "alloc" other no memory leak issue

Jugular answered 6/1, 2010 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.