ios - 识别出 NSURLConnection 的内存泄漏

标签 ios iphone objective-c memory-leaks

当我运行仪器时,我在下面一行中得到了内存链接

NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest 
    returningResponse:&urlResponse error:&error];

有人可以解释一下如何解决这个问题吗

谢谢 萨姆。

- (NSString *)sendHttpsReq:(NSString *) urlString {

     // create the request 
     NSString *endResult = nil;

     NSURL *posHostUrl = [NSURL URLWithString:urlString];
     NSURLRequest *theRequest=[NSURLRequest requestWithURL:posHostUrl
                 cachePolicy:NSURLCacheStorageAllowed
                timeoutInterval:300.0];
     // create the connection with the request
     // and start loading the data 
     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[posHostUrl host]];

     NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];


     if (theConnection) {
      // Create the NSMutableData that will hold
      // the received data
      // receivedData is declared as a method instance elsewhere 


      NSHTTPURLResponse* urlResponse = nil;  
      //NSError *error = [[NSError alloc] init]; 
      NSError *error  = nil;  
      NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&urlResponse error:&error];

      endResult = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];  
            //[error release];

     } else{
      //Inform the user that the connection failed.
      NSLog(@"CONNECTION FAILED");
     }

     [theConnection release];

     return [endResult autorelease];
}

最佳答案

您实际上正在启动两个 NSURLConnections。一种是异步的,一种是同步的。这可能会导致泄漏。

第一个 URLConnection 在以下行中启动:

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

第二个 URLConnection 在以下行中启动:

NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&urlResponse error:&error];

请确保您只下载资源一次。

关于ios - 识别出 NSURLConnection 的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3340972/

相关文章:

ios - TableView 原型(prototype)单元格中的 Collection View

ios - 使用 SLServiceTypeTwitter 时,链接的最长长度是多少?如何设置推文的格式以确保它不会更长?

iphone - 如何查看 nib/xib 文件的代码?

objective-c - 如何始终使 UIScrollView 可滚动?

ios - 使用服务帐户从 iOS 应用上传到 Google Cloud Storage

ios - 当应用程序关闭/终止时 iOS 中的地理围栏

ios - 将自定义的 UITableViewCell 导出到 UIImage

iphone - UITableViewCell - 加载 25 个单元格 - 不要重复使用

ios - UIImage 与 CGImage 的 Swift 等价物?

C++ 后端,Objective C 前端,NULL nil 问题