Reputation: 313
In my app I have to make a HTTP call and I am not interested in the response result from the web service. So I was wondering if it is OK to create a connection and start it and autorelease it not to cause a memory leak.
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:nil];
[connection start];
[connection autorelease];
Is it possible that the garbage collection could destroy the connection object before the HTTP call is made?
Upvotes: 2
Views: 1168
Reputation: 5765
It is understandable that you don't require the response from the server. But don't you want to ensure that a connection was established? What if the connection times out? The client will not even get to know about the error. I feel it is better that you release the connection instance after you have confirmed the the request reached the server.
Also, calling start
in your case is not required, as you are not using initWithRequest:delegate:startImmediately:
method with NO for the startImmediately
parameter.
Upvotes: 1
Reputation: 12366
This is a good question. Even if it is not stated explicitly that the NSURLConnection is retained by the operating system, it appears obvious that the connection request is added as a source of the run loop and then, as such, retained. In any case it should be better for you to set a minimum delegate for the request by just observing the connection termination with
connectionDidFinishLoading:
and after that release your connection object, as written in this part of the documentation:
Finally, if the connection succeeds in downloading the request, the delegate receives the connectionDidFinishLoading: message. The delegate will receive no further messages for the connection and the NSURLConnection object can be released.
For the same reason you should observe the end of connection due to an error with
connection:didFailWithError:
.
Upvotes: 3