Reputation: 7800
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:
NSURLConnection
that's doing work? connectionDidFinishLoading
message is received?invokeSomeWebServiceMethod
and pass self
as part of the connectionWithRequest
message? Then the creation of the NSURLConnection
is encapsulated inside the delegate.Thanks
Upvotes: 0
Views: 246
Reputation: 385870
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 MyDelegate
really is and what object currently hosts invokeSomeWebServiceMethod
.
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.
Upvotes: 1