NSString 被保留后仍被释放
我保留了一个 NSString,唯一释放它的地方是在 dealloc 方法中。然而,由于某种原因,稍后在程序中,当我尝试引用它(具体来说是它的长度)时,我遇到了崩溃,显示 [CFString length]:message sent to deallocated instance 0xff32c50。
我在程序的前面明确保留了该字符串。有什么原因会发生这种情况吗?任何帮助表示赞赏。
字符串entityParameter 在标头中声明,并在稍后定义。 这是一些代码: entityParameter = [[EntitySearchWindow stringByEvaluatingJavaScriptFromString:@"f();"]retain];
我发生崩溃的地方如下所示: if([实体参数长度] != 0 && 实体参数 != nil) { 返回; }
I have an NSString that I've retained, and the only place I release it is in the dealloc method. For some reason, however, later in the program when I try to reference it (its length, specifically), I get a crash, saying [CFString length]:message sent to deallocated instance 0xff32c50.
I explicitly retain the string earlier in the program. Is there any reason why this would be happening? Any help is appreciated.
The string, entityParameter, is declared in the header, and defined later.
Here is some of the code:entityParameter = [[EntitySearchWindow stringByEvaluatingJavaScriptFromString:@"f();"] retain];
The place where I'm getting the crash looks like this:if([entityParameter length] != 0 && entityParameter != nil)
{
return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显然,它不会被保留。
如果“保留”的意思是“分配给属性”,那么您在做什么:
或者:
因为前者将保留(如果该属性被声明为
retain
),而后者则不会。请注意,NSString 属性通常应声明为copy
,但这与问题正交)。如果您的代码如所写:
并且您实际上只在
dealloc
中release
它,然后确保您的包含对象尚未被释放。这可能正在发生。或者可能是您在某处泄漏了字符串引用并在没有保留的情况下虚假地删除了它。在具有“跟踪保留/释放事件”(或任何名称)的仪器中使用僵尸检测应该显示对象上的每个最后保留/释放事件,包括爆炸的事件。
Obviously, it isn't retained, then.
If by "retained" you mean "assigned to a property", are you doing:
Or:
Because the former will retain (if the property is declared as
retain
) whereas the latter will not. Note that NSString properties should generally be declaredcopy
, but that is orthogonal to the question).If your code is as written:
And you really do only
release
it indealloc
, then make sure your containing object hasn't already been deallocated. That may be happening. Or it might be that you've leaked the string reference somewhere and spuriously deleted it without a retain.Using Zombie detection in instruments with "track retain/release events" (or whatever it is called) should show you every last retain/release event on the object, including the one the blew up.