Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between setting an object to nil vs. sending it a release message in dealloc

I have Object:

MyClass *obj= [[MyClass alloc] init];

What's the difference between:

[obj release]; // Only obj own this object.

and:

obj = nil;

Does iOS deallocs obj when i set obj = nil?

I have a pointer, sometime i set it point to an object, sometime do not. So, when i want release a pointer i must check is it nil?

like image 537
asedra_le Avatar asked Nov 18 '10 07:11

asedra_le


People also ask

Is it better to use OBJ nil?

The actual results showed that using obj as a nil check is the fastest in all cases. obj is consistently faster by 30% or more than checking obj. nil? . Surprisingly, obj performs about 3-4 times as fast as variations on obj == nil , for which there seems to be a punishing performance penalty.

What method is automatically called to release object?

Before releasing objects, the CLR automatically calls the Finalize method for objects that define a Sub Finalize procedure. The Finalize method can contain code that needs to execute just before an object is destroyed, such as code for closing files and saving state information.


1 Answers

This answer from the previous decade,

is now only of historic interest.

Today, you must use ARC.

Cheers


The very short answer is DO NOT just set it to nil. You must release it. Setting it to nil has no connection to releasing it. You must release it.

However it's worth remembering that if it is a property, then

self.obj = nil;

will in a fact release it for you. Of course, you must not forget the "self." part !!!!

Indeed,

self.obj = anyNewValue;

will indeed release the old memory for you, clean everything up magically and set it up with the new value. So, self.obj = nil is just a special case of that, it releases and cleanses everything and then just leaves it at nil.

So if anyone reading this is new and completely confused by memory,

  1. You must release it, [x release] before setting it to nil x=nil

  2. IF you are using a property, "don't forget the self. thingy"

  3. IF you are using a property, you can just say self.x=nil or indeed self.x=somethingNew and it will take care of releasing and all that other complicated annoying stuff.

  4. Eventually you will have to learn all the complicated stuff about release, autorelease, blah blah blah. But life is short, forget about it for now :-/

Hope it helps someone.

Again note, this post is now totally wrong. Use ARC.

Historic interest only.

like image 97
Fattie Avatar answered Nov 12 '22 06:11

Fattie