加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 如何检查对象是否已释放?

发布时间:2020-12-16 03:16:32 所属栏目:百科 来源:网络整理
导读:我需要能够检查我是否已经在 objective-c中发布了一个变量.我试过检查它是否变为null: //Checks if buildview is null and returns respective outputif(BuildView == NULL) NSLog(@"Build View Value (pointer): Null");else NSLog(@"Build View Value (po
我需要能够检查我是否已经在 objective-c中发布了一个变量.我试过检查它是否变为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,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

有没有更简单的方法来检查它是否被解除分配?

解决方法

你可能意味着解除分配(被破坏),而不是被释放.被释放并不意味着被释放,这是引用内存管理的重点.被释放不是一个国家,你无法检查它;被摧毁是.

如果你的意思是解除分配,那么不,没有.它被称为弱引用,而Objective-C没有它们用于引用计数.当一个对象被释放时,对它的指针不会自动执行任何操作;他们成了悬空指针.

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

通常,您必须以一种方式设计程序,即在调用它之后不再使用对象指针.在您给出的示例代码中,除了分配新值之外,不得再使用BuildView进行任何其他操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读