views:

29

answers:

1

I have a Objective-C class that makes an HTTP request and, after receiving a response, calls methods on its delegate. The class provides some convenience methods around the built-in NSURLRequest for my application.

My question is: how do I ensure that I release this object? Normally, an object's owner is responsible for ensuring that an object gets released. In this case, there's no obvious owner. I want to create an instance of this class, set its delegate, fire off the HTTP request, and then forget about it (I could be making several of these requests, so the only way to give it an owner would be to keep a list of the request objects in the calling object, which seems suboptimal).

One approach I've considered: when the HTTP response comes in, my object calls its delegate and then does [self autorelease]. The problem is that all clients have to remember not to release this instance (or else my object needs to call retain before it returns to the user).

Anyone have any good patterns for this?

+3  A: 

Apple have already thought of this pattern. On the assumption that you are using NSURLConnection, check out the documentation for -initWithRequest:delegate: Here is what it says about the delegate parameter:

The connection retains delegate. It releases delegate when the connection finishes loading, fails, or is canceled.

[my emphasis]

So when you create the connection, set your object as the delegate. It won't go away until the connection is terminated for whatever reason, even if no other object of yours retains ownership.

By the way, the statement

there's no obvious owner

is false. You say your object has a delegate. The delegate is the obvious candidate to be an owner.

JeremyP