释放对象后需要分配'nil'是什么? [英] What is the need of assigning 'nil' after releasing an object

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

问题描述

我通常在使用后释放该对象

I usually release the object after use by

[myObject release];

但我在一些在线教程中发现他们在发布后指定了 nil 物体。喜欢

But I found in some online tutorials that they assign a nil after releasing the object. Like

[myObject release];
myObject = nil;

是否需要?

推荐答案

关于在释放之后是否需要将指针设置为 nil ,这是一个长期争论的问题,但我对此表示赞同。一个好主意。

It's a long-running debate as to whether setting the pointer to nil after releasing is necessary, but I come down on the side of it being a good idea.

释放对象后,你持有它的指针仍然指向同一个地方。如果您的版本已将保留计数设为0,则将取消分配该对象。如果您尝试向解除分配的对象发送消息,则会收到EXC_BAD_ACCESS错误。但是,在将指针设置为 nil 后向指针发送消息不会出错 - 它只是不会做任何事情。

After the object is released, the pointer you hold to it still points to the same place. If your release has taken the retain count to 0 then the object will be deallocated. If you then try and send a message to the deallocated object you'll get an EXC_BAD_ACCESS error. However, sending a message to the pointer after it's been set to nil won't error - it just won't do anything.

论证的另一面是,如果你要发送一个解除分配的对象,最好知道它并修复你的代码以确保它不会发生。

The other side of the argument is that if you're messaging a deallocated object it's good to know about it and fix your code to make sure it doesn't happen.

两个阵营都有聪明人。

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

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