Why setting to nil after releasing?

前端 未结 4 695
不思量自难忘°
不思量自难忘° 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: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.

提交回复
热议问题