2

What is the difference between these two code snippets:

object = nil;
[object release]

Vs

[object release];
object = nil;

which is the best practice ?

Oliver
  • 23,072
  • 33
  • 138
  • 230
Vignesh Babu
  • 670
  • 13
  • 30

1 Answers1

9
object = nil; 
[object release]

Don't do that. You are sending a release message on a nil object that will just do nothing. But the object that was referenced by your object is still in memory because it has never received a release message.

[object release]; 
object = nil;

Here you release the object, and for convenience and security, you set nil to its reference. So you can call (by mistake of course :-) ) any method on that object and the app won't crash.

But if you use a retained property @property(nonatomic, retain), calling :

self.object = nil;

equals to call :

[object release]; 
object = nil;
Oliver
  • 23,072
  • 33
  • 138
  • 230
  • Hi @Oliver, is that equal for `[object release];` & `[object release];object = nil;` when 'you use a retained property @property(nonatomic, retain)'? – Kjuly Dec 07 '11 at 02:58
  • 1
    @Kjuly:No, if you just release it, it is not set to nil. If you set it just to nil, it is released and set to nil. If you release it and set it to nil, it's the same that just setting it to nil. For a retained property of course. – Oliver Dec 07 '11 at 09:47
  • @Oliver In the last part, you said that setting nil to retain property is equal to release + nil. Can you link to the document ? – onmyway133 Dec 27 '13 at 07:40
  • 1
    @entropy : some searches on the net will help you finding the docv. The point is that when you set a retained property to nil, you remove the link to the "old" object so it is not retained anymore and is released (this is how the retained properties works). And the new value of the property becomes the one you put, so it's nil. – Oliver Dec 30 '13 at 23:44