我们为什么要释放?

编程入门 行业动态 更新时间:2024-10-25 18:34:10
本文介绍了我们为什么要释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我经常看到当我们释放ab对象时,我们立即将其设置为nil。我知道release和nil都释放与对象相关的旧值,但是在释放的情况下,它将对象作为悬挂指针,所以我们必须将其设置为nil。

I often see when we release ab object we immediately set it to nil. I know that release and nil both free the old value associated with object but in case of release it leaves the object as a dangling pointer so we have to set it to nil.

所以我的问题是如果nil释放对象的旧值,并将对象设置为nil为什么我们不应该使用nil为什么w应该使用释放。

So my question is if nil frees the old value of the object and set the object to nil why should not we only use nil why w should use release too.

Way1 :

MyClass *obj = [[MyClass alloc] init]; [obj release]; obj = nil;

Way2:

MyClass *obj = [[MyClass alloc] init]; obj = nil;

如果使用way1为什么不使用way2,way1和way2的真正区别是什么? / p>

What is the real difference in way1 and way2 if use way1 why don't use way2 only?

推荐答案

将指针设置为nil不会释放由该指针的前一个目标占用的内存。

Setting a pointer to nil does not release the memory occupied by the former destination of that pointer. In plain english, assigning it to nil does not release it.

如果您的应用程序是垃圾回收,发布是一个无操作,可以被省略。否则,这是非常,非常必要的。因此,方式1总是正确的,方式2只有在垃圾收集下才是正确的。

If your application is garbage collected, release is a no-op and can be left out. Otherwise, it's very, very necessary. Hence, Way 1 is always correct, and Way 2 is correct only under garbage collection.

注意:此答案不适用于使用自动参考计数。在ARC下,设置指向nil的指针会向对象发送发布。

Note: This answer does not apply to projects using Automatic Reference Counting. Under ARC, setting a pointer to nil does send a release to the object.

更多推荐

我们为什么要释放?

本文发布于:2023-11-24 03:40:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623842.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!