开发者

Does releasing an object destroy the object?

开发者 https://www.devze.com 2023-03-10 10:31 出处:网络
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 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.

  1. If I release this object directly after I make the call, will it destroy the object? (Which I don't want to do.)
  2. 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 my comm 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.

0

精彩评论

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

关注公众号