问题描述
我想知道你目前在什么情况下使用-retainCount
,以及最终使用它可能出现的问题.
I would like to know in what situation did you use -retainCount
so far, and eventually the problems that can happen using it.
谢谢.
推荐答案
你永远不应该使用 -retainCount
,因为它永远不会告诉你任何有用的东西.Foundation 和 AppKit/UIKit 框架的实现是不透明的;您不知道保留了什么、为什么要保留、谁在保留、何时保留等等.
You should never use -retainCount
, because it never tells you anything useful. The implementation of the Foundation and AppKit/UIKit frameworks is opaque; you don't know what's being retained, why it's being retained, who's retaining it, when it was retained, and so on.
例如:
- 您会认为
[NSNumber numberWithInt:1]
的retainCount
为 1.它没有.是 2. - 您会认为
@"Foo"
的retainCount
为 1.它没有.是 1152921504606846975. - 您会认为
[NSString stringWithString:@"Foo"]
的retainCount
为 1.它没有.同样,它是 1152921504606846975.
- You'd think that
[NSNumber numberWithInt:1]
would have aretainCount
of 1. It doesn't. It's 2. - You'd think that
@"Foo"
would have aretainCount
of 1. It doesn't. It's 1152921504606846975. - You'd think that
[NSString stringWithString:@"Foo"]
would have aretainCount
of 1. It doesn't. Again, it's 1152921504606846975.
基本上,因为任何东西都可以保留一个对象(并因此改变它的 retainCount
),并且由于您没有运行应用程序的大多数代码的源代码,一个对象的 retainCount
没有意义.
Basically, since anything can retain an object (and therefore alter its retainCount
), and since you don't have the source to most of the code that runs an application, an object's retainCount
is meaningless.
如果您想找出对象没有被释放的原因,请使用 Instruments 中的 Leaks 工具.如果您想追查对象过早释放的原因,请使用 Instruments 中的 Zombies 工具.
If you're trying to track down why an object isn't getting deallocated, use the Leaks tool in Instruments. If you're trying to track down why an object was deallocated too soon, use the Zombies tool in Instruments.
但不要使用-retainCount
.这真是一种毫无价值的方法.
But don't use -retainCount
. It's a truly worthless method.
编辑
请大家去http://bugreport.apple.com 请求-retainCount
被弃用.要求的人越多越好.
Please everyone go to http://bugreport.apple.com and request that -retainCount
be deprecated. The more people that ask for it, the better.
编辑#2
作为更新,[NSNumber numberWithInt:1]
现在的 retainCount
为 9223372036854775807.如果您的代码期望它是 2,那么您的代码现在已经损坏.
As an update,[NSNumber numberWithInt:1]
now has a retainCount
of 9223372036854775807. If your code was expecting it to be 2, your code has now broken.
这篇关于何时使用 -retainCount?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!