hba
hba

Reputation: 7800

Objective-C Asynchronous Methods and ARC

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:

  1. How does the runtime know not to prematurely wipe-out the NSURLConnection that's doing work?
  2. List item Should I be releasing/closing the connection in my delegate once connectionDidFinishLoading message is received?
  3. Does it make more sense for the delegate to declare the 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

Answers (1)

rob mayoff
rob mayoff

Reputation: 385870

  1. While the connection is downloading, it retains itself.

  2. If you have any strong references to the connection, you should set them to nil once you're done with the connection object.

  3. 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:

allocations instrument options

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:

instruments history for one NSURLConnection

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

Related Questions