为什么在释放后设置为nil? [英] Why setting to nil after releasing?

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

问题描述

我遇到了这个方法:

-(void) someMethod {
    NSMutableArray *anArray = [[NSMutableArray alloc] init]; 
    // Do stuff with anArray ... 
    [anArray release];
    anArray = nil;
}

将数组设置为nil?

这个代码通过发送一个释放消息到数组,它会导致数组被释放。

Is setting the array to nil necessary?
In this code by sending a release message to the array, it will causes the array to be deallocated.

推荐答案

在这种情况下,这是对关键笔划的无意义浪费,因为变量anArray会立即超出范围。

In this case, it is a pointless waste of key strokes because the variable anArray goes out of scope immediately.

在其他情况下,变量在释放指向的对象后仍然保持一段时间,这是一个好主意,因为如果您不小心解除引用,你会得到一个容易发现的EXC_BAD_ACCESS,如果你发送一个消息,它将被忽略(除了返回nil / 0)。

In other cases, where the variable stays in scope for a while after you release the object its pointing to, it is a good idea, because, if you accidentally dereference it, you will get a EXC_BAD_ACCESS which is easy to spot, and if you send a message to it, it will be ignored (except for returning nil / 0).

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

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