如何检查对象是否被释放? [英] How can I check if an object is released?

查看:129
本文介绍了如何检查对象是否被释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够检查是否已经在Objective-c中释放了一个变量.我尝试检查它是否更改为null:

I need to be able to check if I have already released a variable in objective-c. I tried check if it changed to null:

//Checks if buildview is null and returns respective output
if(BuildView == NULL)
    NSLog(@"Build View Value (pointer): Null");
else
    NSLog(@"Build View Value (pointer): Not Null");

//allocates memory and initalizes value
BuildView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

//Checks if buildview is null and returns respective output again
if(BuildView == NULL)
    NSLog(@"Build View Value (pointer): Null");
else
    NSLog(@"Build View Value (pointer): Not Null");

//Releases the view
[BuildView release];

//Checks if buildview is null and returns respective output again
if(BuildView == NULL)
    NSLog(@"Build View Value (pointer): Null");
else
    NSLog(@"Build View Value (pointer): Not Null");

结果是:

Build View Value (pointer): Null
Build View Value (pointer): Not Null
Build View Value (pointer): Not Null

有没有更简便的方法来检查它是否已释放?

Is there any easier way to check if it is deallocated?

推荐答案

您可能是指已释放(已销毁)但未释放. 释放并不意味着被释放,这就是引用计数的内存管理的要点.被释放不是一种状态,您无法检查它;被摧毁.

You probably mean deallocated (destroyed), not released. Being released does not mean being deallocated, that's the point of reference counted memory management. Being released is not a state, you can't check for it; being destroyed is.

如果您的意思是释放,那么没有,没有.它称为弱引用,而Objective-C没有用于引用计数的它们.释放对象时,不会自动对其指针进行任何操作.它们变成了悬空的指针.

If you mean deallocated, then no, there is none. It is called weak reference, and Objective-C does not have them for reference counting. When an object is deallocated, nothing is automatically done to pointers to it; they become dangling pointers.

一种技术是让对象在解除分配期间发送通知,以便拥有指针的所有对象都可以将其重置为nil.

One technique is to have the object send a notification during deallocation, so that everything that holds a pointer can reset it to nil.

通常,您必须对程序进行设计,以使其在调用release之后不再使用对象指针.在给出的示例代码中,除分配新值外,不得将BuildView再次用于其他任何用途.

Generally, you must design your program in a way that no object pointer is used again after you called release on it. In the sample code you've given, you must not use BuildView again for anything else except assigning a new value.

这篇关于如何检查对象是否被释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆