【问题标题】:Is the Apple NSURLConnection Documentation Wrong?Apple NSURLConnection 文档是否错误?
【发布时间】:2011-04-01 21:41:36
【问题描述】:
// 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,我们不是在泄漏内存吗?

如果有的话,你应该什么时候释放连接和接收数据?

【问题讨论】:

    标签: iphone objective-c cocoa-touch memory 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,它将确保没有内存泄漏

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 加载完成后释放连接。连接完成加载或连接失败并出现错误。完成后释放数据。只有当你完成它时,你才能知道。基本内存管理原则。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 2021-05-07
      • 2020-02-14
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多