开发者

Is object free / freed on dealloc and / or release?

I recently took an objective-c test to see how I wo开发者_如何学JAVAuld 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?


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.


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."


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜