I came across this method:
-(void) someMethod {
NSMutableArray *anArray = [[NSMutableArray alloc] init];
// Do stuff with anArray ...
[anArray
No it is not necessary.
It is just for safe reason (to not send a message to a zombie)
And you can test if your ivar is nil or not to realloc:
[ivar release];
ivar=nil;
...
if (ivar==nil) {
ivar = [[NSObject alloc] init];
}
[ivar setValue:@"toto"];
It's not necessary but considered good behaviour to set dangling pointers to nil.
As others have mentioned, setting it to nil
will help your code not crash if you reference the dealloc
ed object. If you reference a dealloc
ed you will get EXC_BAD_ACCESS
error and your app will crash. Since a nil
object returns nil
if a message is sent to it, your app will not crash.
In the example you provide, it is not necessary to nil
it out, since it is contained in a method. However, you do not want to nil
out a variable if you expect to use it somewhere else in the code, since the value will then be nil
.
In this case, it is a pointless waste of key strokes because the variable anArray goes out of scope immediately.
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).