difference between nil and released object
I'm new to Objective-C and and I can't understand this. I know that I ca开发者_如何学编程n send a message to nil (it's so hyped about feature of Objective-C), but I can't send a message to released object, getting an exception in this case, what the difference between them?
nil
is the memory address 0. The runtime knows to not do anything when this address is messaged, because it is the predefined nonexistant object address.
However, a deallocated object will a random memory address, because the pointer isn't cleaned up when the formerly valid object is destroyed. Since it is not the prescribed nonexistant object address, the runtime doesn't know that it's invalid, and will try to send it the message. This will usually crash your program right away.
You can avoid this by setting variables to nil
once you've released them.
nil is 'pointing to nothing', and its allowed to send a message to nil (nothing). An object has a address where its data resists. You use this address to send message and release the object. Like this:
id myObject; // Initialized some where else
[myObject release];
and then send it a message like this:
[myObject someMessage]; // At this point myObject != nil. Not allowed
Then you are actually trying to send a message to the address of the now released object. And this is not allowed.
myObject = nil;
[myObject someMessage]; // Allowed
精彩评论