[objrelease]之后引用计数仍然是1,此时应该释放它

发布于 2024-10-20 05:06:17 字数 379 浏览 2 评论 0原文

当我创建一个对象并检查其保留计数时,我得到了预期的 1。当我释放对象,然后再次检查保留计数时,它仍然是1。难道不应该释放该对象,并且保留计数为0吗?

NSMutableString *str=[[NSMutableString alloc] initWithString:@"hello"];
NSLog(@"reference count is %i",[str retainCount]);
[str release];
NSLog(@"reference count is %i",[str retainCount]);

如果我首先将 str 设置为 nil,我确实会看到保留计数为 0。这是为什么?

When I create an object and check its retain count, I get 1 as expected. When I release the object and then check the retain count again, it is still 1. Shouldn't the object be deallocated, and the retain count 0?

NSMutableString *str=[[NSMutableString alloc] initWithString:@"hello"];
NSLog(@"reference count is %i",[str retainCount]);
[str release];
NSLog(@"reference count is %i",[str retainCount]);

I do see 0 for the retain count if I set str to nil first. Why is that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

单调的奢华 2024-10-27 05:06:17

不要使用 retainCount,它在大多数情况下不会达到您的预期。

您的第二个 NSLog 正在将已释放的内存作为对象进行访问。在这种特殊情况下,释放的内存仍然包含刚刚释放的 NSString 中足够的旧数据,以便在调用 retainCount 方法时程序不会崩溃。如果您使用 NSZombieEnabled 运行此命令,您将收到一条有关向已释放实例发送消息的错误消息。

调用 nil 时返回 0 的原因是,在 nil 对象上调用时返回整数的方法将始终返回 0。

Don't use retainCount, it doesn't do what you expect in most cases.

Your second NSLog is accessing deallocated memory as an object. In this particular case, that deallocated memory still contains enough of the old data from the NSString that was just freed for the program to not crash when the retainCount method is called on it. Had you run this with NSZombieEnabled you would have gotten an error message about sending a message to a deallocated instance.

The reason it returns 0 when called for nil is that methods returning integers will always return 0 when called on a nil object.

誰認得朕 2024-10-27 05:06:17

不要依赖 retainCount。并且不关心这个。很多事情可能会在幕后发生。您只需要确保您已经释放了您拥有的所有东西。如果您想确保没有泄漏任何内存,请使用 Instrument,而不是 NSLog 中的 keepCount。

Do not depend on retainCount. And do not care about this. Lots of things may happen under the hood. You only need to ensure that you have released all the things that you owned. If you are trying to be sure that you are not leaking any memory, then use Instrument, not retainCount in NSLog.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文