views:

47

answers:

2

Hi guys, I'm new to Objective-C and and I can't understand this. I know that I can 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?

A: 

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
Martin Ingvar Kofoed Jensen
+1  A: 

nil is the memory address 0. The runtime knows to not do anything when this address is messaged. However, a deallocated object has a random memory address. Since it can either be valid or not, and the only not too expensive way to know is to try, well, you can message a deallocated object, and it will crash your program.

You can avoid this by setting variables to nil once you've released them.

zneak
@You can avoid this by setting variables to nil once you've released them.Thanks, I didn't know that. But what will happen if a variable has retain count == 2 , and it won't be deallocated after releasing, if I set it to nil, but it has other owner, I won't be good, Im I right?
Burjua
@Aristarh: As soon as you release an object, you should assume it's dead. Don't worry about the other references. The other owners of the object are responsible for releasing it once they're done with it. Therefore, it's "locally safe" to set to `nil` a reference to an object that has been deallocated.
zneak
OK, thanks a lot for explanation, +1 )))
Burjua