2010-08-20 59 views
1
// 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. 
} 

既然我们不通过调用retain来拥有receivedData,我们不是在泄漏内存吗?Apple NSURLConnection文档是否错误?

什么时候你应该释放连接并收到数据?

回答

1

1 /关于连接,我们使用委托模式来处理这种内存管理。你用一种方法分配init并设置委托。然后当你喜欢的连接回调:

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

或者你可以在任何其他委托方法释放连接。这是他们将你连接回去的原因之一。你会遇到这种委托模式很多iPhone一样的UIImagePickerController(只是另一个例子),尤其是在网络问题时,你必须等待,直到网络完成释放

2 /从评论,

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

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

0

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

+0

你在哪里发布? – 2010-08-20 22:30:07

+1

完成加载后释放连接。无论是在连接完成加载或连接确实失败,错误。完成后释放数据。只有你可以知道你什么时候做完了。基本的内存管理原则。 – Jasarien 2010-08-20 23:32:40