Sheehan Alam
Sheehan Alam

Reputation: 60909

dealloc or releasing best practice in objective-c?

I just simply release objects as such:

[myObj release];

I have seen others add:

[myObj release]; myObj = nil;

Is the latter more advantageous because now there will never be a reference to that pointer?

Upvotes: 0

Views: 182

Answers (2)

Girish Kolari
Girish Kolari

Reputation: 2515

According to me this is purely depend on the scope of myObject.

  1. If myObject scope is getting ended with the release statement then there is no advantage in setting it to nil

  2. If myObject scope don't end with release statement then setting the object to nil make your object access safe. There is good chance that myObject memory is released and you try to access this memory location which will lead to exception.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816780

It is just to make sure that other successive messages that might be send to myObj don't throw an exceptions. Message send to nil are possible in Objective-C.

Otherwise, myObj still points to the memory address where it has been and accessing it might result in a BAD_ACCESS error.

Upvotes: 4

Related Questions