Why does sending retainCount to @“Hi” return -1?

天涯浪子 提交于 2020-01-23 12:41:56

问题


The method retainCount is supposed to return an unsigned integer.

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


回答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)




回答2:


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?




回答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.




回答4:


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.




回答5:


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

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



来源:https://stackoverflow.com/questions/2014667/why-does-sending-retaincount-to-hi-return-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!