释放后将指针设置为nil? [英] Set pointers to nil after release?

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

问题描述

释放对象后,最好将指针设置为nil吗?那就是我一直在做的,只是想问一问是否有必要,良好的做法或过大的杀伤力?

After releasing objects is it best to set the pointers to nil? Thats what I have been doing, just wanted to ask if its necessary, good practice or overkill?

- (void)dealloc{
    [planetName release]; // NSString instance variable
    [super dealloc];
}
@end

.

- (void)dealloc{
    [planetName release]; // NSString instance variable
    planetName = nil;
    [super dealloc];
}
@end

欢呼-加里-

推荐答案

取决于保存指针的变量的范围.如果指针在范围内继续存在,我总是将其设置为nil,以防万一我在其他地方再次调用该变量.否则,就有可能访问包含现在已释放的对象的内存位置.

Depends on the scope of the variable that holds the pointer. I always set pointers to nil if they continue to exist within the scope, just in case I'm calling the variable again somewhere else. Otherwise, there's a risk that I would access a memory location that contained an object which is now released.

但是,如果变量超出范围,则也不会使用该变量,因此将nil分配给它有点过大.不过,如果其他人决定将代码添加到您的代码中并意外地在变量范围内但又将其释放后再次使用该变量,则最好仅分配nil.

But if the variable goes out of scope, then it won't be used either, thus assigning nil to it is a bit overkill. Still, it is a good practice to just assign nil just in case someone else decides to add code to your code and accidently uses the variable again within it's scope but after it was freed.

这篇关于释放后将指针设置为nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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