为什么在Obj-C中发送释放消息后将对象设置为nil [英] Why set object to nil after sending release message in Obj-C

查看:57
本文介绍了为什么在Obj-C中发送释放消息后将对象设置为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试在不再需要对象时从内存中释放它们时,我看到许多具有以下语法的Objective-C代码.

I see a lot of Objective-C code that has the following syntax when attempting to free objects from memory when they are no longer needed.

[controller release], controller = nil;

为什么在发送释放消息后将变量设置为nil?释放不会释放对象吗?为什么也需要将其设置为nil.

Why set the variable to nil after sending the release message? Isn't release going to free the object no matter what? Why does it need to be set to nil as well.

这只是Obj-C中的一种老派"做事方式,还是比我想象的还要多?

Is this just an "old-school" way of doing things in Obj-C, or is there more to it than I realize?

推荐答案

在对象上调用release并不一定意味着它将被释放.它只是减少对象的保留计数.直到保留计数达到0为止,对象才被释放(即使那样,对象可能在自动释放池中,但那时还没有被释放).

Calling release on an object does not necessarily mean it's going to be freed. It just decrements the object's retain count. It's not until the retain count reaches 0 the object gets freed (and even then, the object might be in an autorelease pool and still not be freed quite then).

因此,您可以释放对象,但仍可以指向它.然后它可以自动发布.然后,您向它发送一条消息-但现在该对象可能是垃圾.不好.

So, you might release your object but you could still be pointing to it. And then it could get autoreleased. And then you send it a message — but maybe the object is garbage now. That's bad.

在释放指针后将其设置为nil意味着您无法将消息发送到已垃圾回收的对象.您已经完成了该对象的操作,可以说nil想要说的话,没有造成任何伤害.

Setting your pointer to nil after releasing it means you can't send a message to a garbaged object. You're done with that object, and you can say whatever you want to nil, no harm done.

这篇关于为什么在Obj-C中发送释放消息后将对象设置为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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