Iphone Apple NSURLConnection文档是否错误?

Iphone Apple NSURLConnection文档是否错误?,iphone,objective-c,cocoa-touch,memory,nsurlconnection,Iphone,Objective C,Cocoa Touch,Memory,Nsurlconnection,既然我们不通过调用retain来“拥有”接收数据,我们不是在泄漏内存吗 您应该何时释放连接并接收数据(如果有)?此代码同时拥有连接和数据。连接是用alloc/init创建的,需要稍后发布,并且数据被保留,因此也需要发布。此代码同时拥有连接和数据。连接是使用alloc/init创建的,需要稍后发布,并且数据会保留,因此也需要发布。1/关于连接,我们使用委托模式来处理该连接的内存管理。您可以在一个方法中分配init并设置委托。然后在您喜欢的连接回调时: // Create the request.

既然我们不通过调用retain来“拥有”接收数据,我们不是在泄漏内存吗


您应该何时释放连接并接收数据(如果有)?

此代码同时拥有连接和数据。连接是用alloc/init创建的,需要稍后发布,并且数据被保留,因此也需要发布。

此代码同时拥有连接和数据。连接是使用alloc/init创建的,需要稍后发布,并且数据会保留,因此也需要发布。

1/关于连接,我们使用委托模式来处理该连接的内存管理。您可以在一个方法中分配init并设置委托。然后在您喜欢的连接回调时:

// 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.
}
也可以在任何其他委托方法中释放连接。这是他们将连接传还给您的原因之一。在类似iPhone的UIImagePickerController中,您会经常遇到这种委托模式(仅举另一个例子),尤其是在网络问题中,当您必须等待网络完成发布时

2/根据评论

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

所以,这很容易回答,因为receivedData是一个实例变量,您应该并且可以在
dealoc
方法中释放它。您的另一个选择是为它声明一个
@属性(非原子,retain)
,然后它将确保没有内存泄漏如果您多次设置receivedData

1/关于连接,我们使用委托模式来处理该属性的内存管理。您可以在一个方法中分配init并设置委托。然后在您喜欢的连接回调时:

// 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.
}
也可以在任何其他委托方法中释放连接。这是他们将连接传还给您的原因之一。在类似iPhone的UIImagePickerController中,您会经常遇到这种委托模式(仅举另一个例子),尤其是在网络问题中,当您必须等待网络完成发布时

2/根据评论

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

所以,这很容易回答,因为receivedData是一个实例变量,您应该并且可以在
dealoc
方法中释放它。您的另一个选择是为它声明一个
@属性(非原子,保留)
,然后如果多次设置receivedData,它将确保没有内存泄漏

在连接完成加载时释放连接。连接中没有完成加载,或者连接失败并出现错误。完成后释放数据。只有你才能知道你什么时候完成了。基本内存管理原则。完成加载后释放连接。连接中没有完成加载,或者连接失败并出现错误。完成后释放数据。只有你才能知道你什么时候完成了。基本内存管理原则。