Why setting to nil after releasing?

前端 未结 4 693
不思量自难忘°
不思量自难忘° 2021-01-03 16:08

I came across this method:

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


        
相关标签:
4条回答
  • 2021-01-03 16:42

    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"];
    
    0 讨论(0)
  • 2021-01-03 16:42

    It's not necessary but considered good behaviour to set dangling pointers to nil.

    0 讨论(0)
  • 2021-01-03 16:53

    As others have mentioned, setting it to nil will help your code not crash if you reference the dealloced object. If you reference a dealloced 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.

    0 讨论(0)
  • 2021-01-03 16:57

    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).

    0 讨论(0)
提交回复
热议问题