何时使用-retainCount? [英] When to use -retainCount?

查看:54
本文介绍了何时使用-retainCount?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道到目前为止您在什么情况下使用过-retainCount,最终想知道使用它会出现的问题.

谢谢.

解决方案

您永远不要使用-retainCount,因为它永远不会告诉您任何有用的信息. Foundation和AppKit/UIKit框架的实现是不透明的.您不知道要保留的内容,为什么要保留它,谁要保留它,何时保留它,等等.

例如:

  • 您会认为[NSNumber numberWithInt:1]retainCount为1.事实并非如此.是2.
  • 您会认为@"Foo"retainCount为1.事实并非如此.是1152921504606846975.
  • 您会认为[NSString stringWithString:@"Foo"]retainCount为1.事实并非如此.再次是1152921504606846975.

基本上,由于任何事物都可以保留对象(并因此更改其retainCount),并且由于您没有运行应用程序的大多数代码的源代码,因此对象的retainCount是毫无意义的.

如果您要查找为什么未释放对象的原因,请使用仪器中的泄漏"工具.如果您试图找出为什么对象被过早释放的原因,请使用Instruments中的僵尸"工具.

但不要使用-retainCount.这是一种毫无价值的方法.

修改

请所有人访问 http://bugreport.apple.com ,并要求弃用-retainCount.要求的人越多越好.

修改#2

作为更新,[NSNumber numberWithInt:1]现在具有retainCount的9223372036854775807.如果您的代码期望它为2,则您的代码现在已损坏.

I would like to know in what situation did you use -retainCount so far, and eventually the problems that can happen using it.

Thanks.

解决方案

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.

For example:

  • You'd think that [NSNumber numberWithInt:1] would have a retainCount of 1. It doesn't. It's 2.
  • You'd think that @"Foo" would have a retainCount of 1. It doesn't. It's 1152921504606846975.
  • You'd think that [NSString stringWithString:@"Foo"] would have a retainCount of 1. It doesn't. Again, it's 1152921504606846975.

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.

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.

But don't use -retainCount. It's a truly worthless method.

edit

Please everyone go to http://bugreport.apple.com and request that -retainCount be deprecated. The more people that ask for it, the better.

edit #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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆