[objrelease]之后引用计数仍然是1,此时应该释放它
当我创建一个对象并检查其保留计数时,我得到了预期的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用
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 theretainCount
method is called on it. Had you run this withNSZombieEnabled
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.
不要依赖
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.