如何确定我是否有指针释放对象? [英] How to determine if I have a pointer to released object?
问题描述
在一个函数中,我正在处理一个可能被破坏的对象,在运行时,我可以以某种方式确定我的对象是否被破坏?
In a function I am processing an object which may be corrupted sometimes, at runtime, can I somehow determine whether or not my object is corrupted?
推荐答案
真正做到这一点的唯一方法是利用ARC(和iOS 5,在此之前不起作用)利用一个新的东西称为 __ weak
指针
The only way to really do this is to leverage a new thing with ARC (and iOS 5, doesn't work before this) called __weak
pointers.
根据定义,还应注意 __ weak
变量不保留。如果 __ weak
变量保留它的目标,那么根据定义,它不能自己释放。
It should also be noted that __weak
variables do not retain, by definition. If a __weak
variable retained it's target, then by definition, it couldn't release itself.
基本上, __ weak
指针是一个变量,当它被释放时,它自动设置为 NULL
。因此,您可以执行此操作来确定对象是否被取消分配:
Basically, a __weak
pointer is a variable that automatically set's itself to NULL
when it is deallocated. Thus, you can do something like this to determine if an object is deallocated:
__strong id object; // required so that the object doesn't get deallocated right away
__weak id _weakRef;
object = [NSObject new];
_weakRef = object;
// do stuff with 'object'
if (_weakRef)
{
// 'object' hasn't been deallocated yet, do something with it.
}
通常来说,你不会坚持强弱弱的参考对象,但是,因为这导致 _weakRef
无用(只需检查你设置对象
到
Normally speaking, you don't hold onto a strong and weak reference to an object, however, as this causes _weakRef
to be useless (just check when you set object
to nil
).
我也会警惕,只能设计一个基于 __ weak $ c $的设计模式c>变量,特别是如果你正在制作一个框架。没有什么说烦人就像使用iOS 5作为目标部署。
I would also caution against having a design pattern based solely on __weak
variables, especially if you are making a framework. Nothing says 'Annoying' like having to use iOS 5 as your target deployment.
我希望这篇文章能帮助您更深入地了解弱引用如何工作,如果不是有一个很好的维基百科文章,您可以在这里阅读:
I hope this post helped you get a deeper understanding of how weak references work, and if not, there is an excellent wikipedia article you can read here:
http: /en.wikipedia.org/wiki/Weak_reference
这篇关于如何确定我是否有指针释放对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!