Reputation: 1675
Can I create an NSURLConnection
object with an asynchronous request in applicationDidFinishLaunching:
, and not keep a reference to it in an instance variable, as follows?
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSURLConnection *localVariable = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}
I believe this should work when not using ARC. While I no longer have any reference to the NSURLConnection
object, it should do its job and not get deallocated until I release it in one of its delegate methods, like connectionDidFinishLoading:
, because it leaves applicationDidFinishLaunching:
with a retain count of +1, right?
The question, however, is: Is this considered bad style? Should I always maintain an instance variable with this kind of object relationship? What would I do to make this work with ARC? After all, when localVariable
goes out of scope, ARC would deallocate my NSURLConnection
, I suppose.
Upvotes: 2
Views: 334
Reputation: 539845
I could not find an official reference for this, but it seems that an NSURLConnection
created with initWithRequest
keeps a strong reference to itself, to prevent it from being deallocated. This reference is deleted only after the final delegate function has been called, or the connection has been canceled.
(See e.g. been having a little confusion about the retainCount of NSURLConnection or http://www.cocoabuilder.com/archive/cocoa/110116-nsurlconnection-retaincount-at-initialisation.html)
Therefore your code works also with ARC: Even when localVariable
goes out of scope, there is another reference to the connection as long as the connection is "active".
This means that you don't have to keep a reference to the connection. But it is useful because it enables you to cancel the connection if necessary.
Upvotes: 4