我们为什么要释放? [英] Why should we release?

查看:106
本文介绍了我们为什么要释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到当我们释放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.

这篇关于我们为什么要释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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