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
DataFinishedLoadingevent on mycommobject. 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
releaseonly destroys the object if the last retainer released it.For example, say you allocate your
Communicationobject. It is implicitly retained once. Then you retain it five times. You need to release/autorelease the object six times until it gets destroyed (itsdeallocmethod is called).There is an internal counter, the
retainCount. When you create an object, it is set to1. Now everyretainincreases the counter, and everyreleasedecreases it.autoreleasealso 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’sdealloc). Warning: do not rely on theretainCount, do not even look at it. You should only care that youralloc/copy/new/retaincalls are balanced with a correspondingrelease/autoreleaselater on.