为什么发送retainCount到@“Hi”会失败?返回-1?
方法 retainCount
应该返回一个无符号整数。
那么为什么[@"Hi"retainCount]
返回-1?
The method retainCount
is supposed to return an unsigned integer.
Why then, does [@"Hi" retainCount]
return -1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
简单的答案是,因为
@"Hi
" 是一个字符串文字,它总是位于二进制可执行映像中,并且永远不会“消失”,因此保留/释放没有效果,你会看到UINT_MAX
(打印出来时看起来像-1,例如用%d签名)。 (参见 Pete Kirkham 关于具有这些语义的 NSObjects 的回答)。除此之外,了解虽然 @"Hi" 的行为类似于 NSString* 是很有用的,但它实际上是编译器创建的类 CFConstantString 的实例(或者可能是 NSConstantString,我的调试器不同意某些文档),它包装文字字符串数据并为您提供 NSString* 接口。但编译器知道这些字符串很特殊并且永远无法清理,因此它们的保留计数始终为 UINT_MAX (-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 seeingUINT_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 classCFConstantString
(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)根据苹果的 NSObject 文档,对于从未释放的对象,它应该返回
UINT_MAX
。如果您将UINT_MAX
打印为有符号整数,通常会得到-1
,这可能就是您正在做的事情 - 您如何输出该值?According to Apple's NSObject documentation, it should return
UINT_MAX
for objects which never get released. If you printUINT_MAX
as a signed int, you typically get-1
, which may be what you're doing - how are you outputting the value?永远不要依赖
retainCount
方法。 Cocoa 在幕后进行了各种优化,这使得retainCount
方法不可靠且无用。甚至苹果公司也不鼓励使用它。坚持为 Cocoa 设置的内存管理规则,您将永远不需要知道任何对象的retainCount
。Don't ever rely on the
retainCount
method. Cocoa makes all sorts of optimisations behind-the-scenes which makes theretainCount
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 theretainCount
of any object.有符号整数和无符号整数之间的唯一区别在于如何解释该值。如果将 -1 作为无符号整型读取,您会发现它是无符号整型的最大值。
例如: NSLog(@"%u", [@"Hello" keepCount]);
它之所以这么大,是因为常量字符串对象永远不会被释放。
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”不需要用代码释放,
只需注意由“alloc”创建的对象,其他没有内存泄漏问题
@"Hello" is not required to release with code ,
just be care for the object was create by "alloc" other no memory leak issue