I’m new to Objective-c. I wrote a few lines of code to access a web-service asynchronously and then process the results. Could you please explain how the ARC works when an asynchronous method takes a delegate (protocol) as an argument?
For example I’m invoking the web-service by using a local NSURLConnection in a method:
-(void) invokeSomeWebServiceMethod {
MyDelegate *const theDelegate = ...;
NSURL *const url = ...;
NSURLRequest *const request = ...;
[NSURLConnection connectionWithReuqest: request delegate:theDelegate];
}
I wasn’t sure this approach would work, since the implicit NSURLConnection which is returned as a result of the connectionWithRequest message should be marked for clean-up, because neither the calling method nor the delegate has a reference to it. But it works!
So:
- How does the runtime know not to prematurely wipe-out the
NSURLConnectionthat’s doing work? - List item Should I be releasing/closing the connection in my delegate once
connectionDidFinishLoadingmessage is received? - Does it make more sense for the delegate to declare the
invokeSomeWebServiceMethodand passselfas part of theconnectionWithRequestmessage? Then the creation of theNSURLConnectionis encapsulated inside the delegate.
Thanks
While the connection is downloading, it retains itself.
If you have any strong references to the connection, you should set them to nil once you’re done with the connection object.
To answer this question, I need more information about what
MyDelegatereally is and what object currently hostsinvokeSomeWebServiceMethod.You can look at the retains and releases yourself by running your app under the Allocations instrument with “Record reference counts” enabled and “Only track active allocations” disabled:
Then, after running your program under Instruments, you can type “NSURLConnection” into the search bar and drill down by clicking the little white arrows in gray circles to see the trace for a single object:
You can see in that screen shot (right-click and open in a new tab for full size) that
-[NSURLConnectionInternal initWithInfo:]retains the connection (line 1). That retain is balanced by a release later after the connection has finished sending all of its delegate messages.