Does releasing an object destroy the object?
I am new to cocoa-touch, and really unmanaged languages all together. While I have a firm grasp of the syntax, I am questioning whether I am releasing an object correctly.
I have a view that creates an object开发者_运维技巧,
Communication *comm = [[Communication alloc] init];
[comm doSomething];
[comm release];
I understand that I have to destroy this object because I am allocating it and it will not auto release.
I call a method on the object that goes out to my server and grabs information. When the data returns it throws an event which my "message dispatcher" responds to. I do not want to destroy the object until it returns back from the server -- and this is where my confusion is at.
- If I release this object directly after I make the call, will it destroy the object? (Which I don't want to do.)
- How do I properly destroy this object after it throws the event with the data I am waiting for? This would occur within a
DataFinishedLoading
event on mycomm
object. Should it destroy itself, and is this the right way to do it?
The view calling my object essentially says, create this object, call this method, and go about your merry way. It doesn't care about what happens after it calls the method -- whether it brings back information or not. It simply listens on a method for any data that may come across at a later time. I have no reason to hang onto a reference of the object, as I will never use the same instance after I make the call -- that is besides cleaning up after myself.
A release
only destroys the object if the last retainer released it.
For example, say you allocate your Communication
object. It is implicitly retained once. Then you retain it five times. You need to release/autorelease the object six times until it gets destroyed (its dealloc
method is called).
There is an internal counter, the retainCount
. When you create an object, it is set to 1
. Now every retain
increases the counter, and every release
decreases it. autorelease
also decreases the counter, but not immediately. Once the counter drops to 0 Objective-C knows that the object is no longer needed and destroys it (by calling the object's dealloc
). Warning: do not rely on the retainCount
, do not even look at it. You should only care that your alloc/copy/new/retain
calls are balanced with a corresponding release/autorelease
later on.
In your above example, comm
will likely be destroyed when you call release
. It depends on something else retains it during doSomething
.
If you want to hold onto an object while it does something asynchronously, put it in a retained property. When it informs you that it is done, set the property to nil
which will release it.
精彩评论