引用计数在[obj release]之后仍然是1,当它应该被释放 [英] Reference count is still 1 after [obj release], when it should be deallocated
问题描述
当我创建一个对象并检查其保留计数,我得到1如预期。当我释放对象,然后再次检查保留计数,它仍然是1.不应该释放对象,并保留计数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]);
如果设置<$ c,我 $ c> str 到 nil
。为什么?
I do see 0 for the retain count if I set str
to nil
first. Why is that?
推荐答案
不要使用 retainCount
您的第二个 NSLog
正在访问作为对象的释放内存。在这种特殊情况下,释放的内存仍然包含足够的来自NSString的旧数据,只要在调用 retainCount
方法时,程序不会崩溃。如果你使用 NSZombieEnabled
运行这个命令,你会收到一条关于向一个释放的实例发送消息的错误消息。
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.
调用nil时返回0的原因是,当调用nil对象时,返回整数的方法总是返回0。
The reason it returns 0 when called for nil is that methods returning integers will always return 0 when called on a nil object.
这篇关于引用计数在[obj release]之后仍然是1,当它应该被释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!