I am wondering, does local variable need to set to nil to deallocate the variable after use?
3 Answers
No. The memory is deallocated based on its retain count. Once that goes to zero it will be deallocated regardless of the value of the variable that used to point to it. Setting a variable to nil is a good practice so you don't try to access deallocated memory.

- 19,799
- 4
- 52
- 98
-
Why does this code work? `self.a = @"Hello"; [self.a release]; NSLog(@"%@", self.a); ` and prints `Hello` – Akshit Zaveri Sep 15 '17 at 13:28
-
@AkshitZaveri Good question. There are rules around when the deallocation happens but this is managed by the runtime. NSString especially is magic: https://stackoverflow.com/a/1390394/901059 The runtime takes liberties so rely on following the rules over observed behavior. – N_A Sep 15 '17 at 15:20
No.
If you are using ARC, any strong variables will be released when the variable goes out of scope (your method returns or block closes). Setting the variable to nil
at the end will have no effect.
If you are not using ARC, then be sure to call release
or autorelease
on objects you own. Once that is done, you have removed your claim on the object and it can be deallocated.

- 39,734
- 6
- 101
- 123
The only time setting to nil has any effect is when either using the setFoo: method or dot notaion for setting a property. If you merely set an instance variable to nil instead of using the dot notation or method, you will actually leak memory. Keeping this in mind, you can see why, no, setting a local variable to nil has no effect at all.
You should take a look at https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html to get a better idea of how reference counting works. Basically, if you called alloc on it, you also have to release it.

- 181
- 1
- 4