Leonardo
Leonardo

Reputation: 9857

Deallocated instance and nil object in objective-c

Coming from a java background, where everything goes under null pointer exception, I found some difficulties in understanding the difference between nil and deallocated instance in objective-c.

In objective-c it is known that sending a message to a nil object is not sorting any effect to the program flow.

However, sending a message to a deallocated object result in message to deallocated instance error.

In my ideal world a deallocated instance is 'nil', but obviously is not.

The precise question are:

Upvotes: 2

Views: 543

Answers (2)

Odrakir
Odrakir

Reputation: 4254

I think the problem is you have to differentiate between two things: objects and pointers to those objects.

The pointers are the ones that can be nil or not. And the objects are the ones that can be deallocated.

So sending a message through a nil pointer is ok. The Objective-C runtime is smart enough to keep program flow and just return 0. But if the object being pointed from that pointer is deallocated, then, there's something wrong with your program (you are deallocating an instance that still has some retain counts) and it should crash.

Upvotes: 1

Cy-4AH
Cy-4AH

Reputation: 4615

  1. It frees allocated memory (deallocate it) and resources.
  2. Not important. If you will not use pointer any more, than you can leave it as is.

Upvotes: 0

Related Questions