开发者

Is the Apple NSURLConnection Documentation Wrong?

// 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 elsewh开发者_如何转开发ere.
    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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜