简体   繁体   中英

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:

  • what happens to the object when it is deallocated ?
  • If the object is deallocated, shouldn't it be freed, and then become nil ?

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.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM