views:

58

answers:

2
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
}

Since we dont' "own" receivedData by calling retain on it, aren't we leaking memory?

When are you supposed to release connection and receivedData if at all?

A: 

This code owns both the connection and the data. The connection is created with alloc/init, requiring a release later, and the data is retained, so that too will require a release.

Jasarien
where do you release?
Sheehan Alam
Release the connection when its finished loading. Either in connection did finish loading or connection did fail with error. Release the data when you're done with it. Only you can know when you're done with it. Basic memory management principles.
Jasarien
A: 

1/ About the connection, we use the delegate pattern to handle the memory management of this. You alloc init and set the delegate in one method. And then when the connection callback you like:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  [connection release];
}

or you can release the connection in any other delegate methods. This is one of reasons why they pass you back the connection. You will meet this delegate pattern a lot in iPhone like UIImagePickerController (just for another example), especially in networking problems when you have to wait until the network finish to release

2/ From the comment,

// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.

So, that is easy to answer, because receivedData is an instance variable, you should and can release it in dealloc method. Another choice for you is to declare a @property (nonatomic, retain) for it and then it will make sure no memory leak if you set the receivedData multiple times

vodkhang