views:

75

answers:

3

I recently took an objective-c test to see how I would do.

Turns out my score wasn't anywhere near as good as I hoped. That means more studying.

During the test, I was asked this question:

How do you free an object?

A. [obj dealloc]; B. [obj release]; C. None of the above

My choice was A, and I don't know if it's correct. The question is confusing: Doesn't release call dealloc, therefore achieving the same result?

+6  A: 

No. release decrements the object's reference count.

You don't call dealloc directly. Call release to decrement the reference count and let the runtime call dealloc when the reference count becomes zero.

Abizern
Aha - makes sense. Thanks - guess I was wrong!
just_another_coder
Actually, release signals that you have relinquished your claim on ownership, no more, no less. In practical terms, it usually means that the retain count of the object will be decremented, but not always e.g. inspect the retain count of a constant string before and after releasing it.
JeremyP
A: 

Yes, release does call dealloc but only after decrementing the reference count and only if the reference count went to zero. The NSObject class reference says that release:

"Decrements the receiver’s reference count."  

"The receiver is sent a dealloc message when its reference count reaches 0."
progrmr
That doesn't mean that release chains a call to dealloc though. GC will send that dealloc on a reference check. Just wanted to clarify.
Jordan
GC will never, ever, send `dealloc`.
bbum
How about a non GC environment? That's what I was thinking about.
progrmr
A: 

I know an answer has already been accepted for this, but I can't resist adding my own thoughts.

The answer to the test question is technically C. You don't free objects, the runtime frees them when it thinks they are no longer in use.

If you release an object in the reference counted environment, you are not freeing it, merely indicating that you are relinquishing any claim of ownership. When nobody has an ownership claim, dealloc is called by the runtime and the object is freed. Similarly, in the garbage collected environment, when you overwrite a reference, you are signalling that you are no longer interested in it. Once all references have gone, at some indeterminate time later, finalize is sent to the object and the object is freed.

JeremyP