views:

368

answers:

1

NSURLConnection *connection is a property of the class

@property (nonatomic, retain) NSURLConnection *connection;

Instruments is reporting that I'm leaking an NSURLConnection object in the second line of the code below.

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];

In the didFinishLoading and didFinishWithError delegate selectors, I'm releasing the connection and setting to nil

[self.connection release];
self.connection = nil;

I've read the "NSURLConnection leak?" post and several others. I feel like I must be missing something totally obvious. Help?

+2  A: 

As the comment from roe said, you are allocating the connection (retain count 1) and then retaining it again with your connection property (retain count 2). You only release once in the delegate selectors. You have two options:

1) Change your connection property to assign rather than retain.

@property (nonatomic, assign) NSURLConnection *connection;

// OR, since assign is the default you may omit it

@property (nonatomic) NSURLConnection *connection;

2) Release the allocated object after it is retained by your connection property:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = connection;
[connection release];
[request release];

Option 2 is preferred since there is less of a chance for leaks since alloc and release are as close together as possible. Also, if you forget to release the previous connection the synthesized methods will release the previous one for you. Don't forget to release self.connection in dealloc.

James Wald
Thanks very much!!
TomH
Oops I meant to say "as roe said." Glad to help.
James Wald