I usually release the object after use by
[myObject release];
But I found in some online tutorials that they assign a nil after releasing the object. Like
[myObject release];
myObject = nil;
Is it required?
It's a long-running debate as to whether setting the pointer to nil
after releasing is necessary, but I come down on the side of it being a good idea.
After the object is released, the pointer you hold to it still points to the same place. If your release has taken the retain count to 0 then the object will be deallocated. If you then try and send a message to the deallocated object you'll get an EXC_BAD_ACCESS error. However, sending a message to the pointer after it's been set to nil
won't error - it just won't do anything.
The other side of the argument is that if you're messaging a deallocated object it's good to know about it and fix your code to make sure it doesn't happen.
There are smart people in both camps.
No, it is not strictly required.
If your code is well-structured there's no need to force myObject
to be equal to nil.
However it may be a good habit: release
does not immediately destroy the object, just decrease the retain
count. Thus it may be,that, even if you call release, the object will still be there for a while, creating problems if you try to send it messages.
Using myObject = nil;
eliminate this problem, since, even if you send a message to myObject
nothing will actually happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With