【问题标题】:Getting leak in leak in [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil]在 [NSURLConnection sendSynchronousRequest:theRequest returnedResponse:nil error:nil] 中获取泄漏
【发布时间】:2011-03-08 04:04:13
【问题描述】:

我有泄漏 returnData= [NSURLConnection sendSynchronousRequest:theRequest returnedResponse:nil error:nil];

下面是我正在使用的代码

    NSString* curl = @"https://Some Url?ticket=";
curl = [curl stringByAppendingString:self.ticket];
curl = [curl stringByAppendingString:@"&apikey=hjgajgfjaghjf&XMLString="];
curl = [curl stringByAppendingString:stringB];
curl = [curl stringByReplacingOccurrencesOfString:@"\n" withString:@""];
NSURL *finalURL = [NSURL URLWithString:curl];

    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:finalURL cachePolicy:NSURLRequestReloadIgnoringCacheData   timeoutInterval:10]; 
     [theRequest setHTTPMethod:@"POST"];

   NSData* returnData= [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];

谁能告诉我为什么我在 returndata 中泄漏了我重新释放了 returndata 并尝试了它,但我仍然得到了。

谢谢

【问题讨论】:

    标签: objective-c memory-leaks iphone-sdk-3.0 nsurlrequest


    【解决方案1】:

    从您发布的代码来看,没有泄漏。有可能当你最终返回 returnData 时,调用者可能会保留它而忘记释放它,但你提供的代码的 sn-p 中的所有对象都是自动释放的,并将在当前运行循环结束时释放。

    我能想到的几点:

    1. 您是否可能在后台线程中运行此程序(通过 performSelectorInBackground:withObject: 或使用显式 NSThread 分配)并且忘记创建并稍后在代码周围耗尽 NSAutoreleasePool?

    2. 您可能在 NSURLConnection 的缓存中占用了内存。您没有提到导致您认为 returnData 泄漏的原因,但如果它只是该区域的内存丢失(与 Leaks Instrument 专门标记 returnData 对象相反),那么您可以通过清除来释放 RAM NSURLConnection 使用 [[NSURLCache sharedURLCache] removeAllCachedResponses];

    3. 之类的东西显式缓存
    4. 虽然与那里的任何实际泄漏无关,但使用NSString-stringWithFormat: 而不是多次调用-stringByAppendingString: 来构建您的URL 字符串会稍微更有效率。同样,所有内容都是自动释放的,因此字符串处理中没有泄漏,但您会创建更少的临时对象并在下一次 NSAutoreleasePool 耗尽之前减少峰值内存使用量。

    我要寻找解决方案的第一个地方是此代码的调用者。很有可能它保留了这个方法的返回值并且在某些时候没有正确地释放它。它也可能将返回分配给保留的@property,而不是最终在-dealloc 中将属性归零,仪器会告诉您首次分配泄漏内存的位置,但它无法知道实际泄漏的位置发生 -- 当包含指针的最后一个变量被覆盖或超出范围时。

    如果您还没有,请尝试使用 Xcode 的构建和分析功能编译您的代码。由该函数运行的 CLANG 静态分析器通常可以比 Instruments 中的运行时动态分析更能找出您最后一个参考丢失的位置。

    祝你好运!泄漏从来都不是一件有趣的事......

    【讨论】:

      【解决方案2】:

      我遇到了相反的问题。我无法让它清除缓存。所以这就是我所做的:我添加了另一对总是不同的,使 URL 总是有点不同。我补充说:

      [...]
      
      curl = [curl stringByAppendingString:@"&hello=hello"];
      
      curl = [curl stringByAppendingString:nowStr];
      
      where nowStr:
      
      NSDate *now = [NSDate date];
      
      NSString * nowStr = [NSString stringWithFormat:@"%@", now];
      
      nowStr = [nowStr stringByReplacingOccurancesOfString:@" " withString:@""];
      
      nowStr = [nowStr stringByReplacingOccurancesOfString:@"+" withString:@""];
      

      我确定我应该使用一些与随机数有关的东西,也许我以后会这样做。

      【讨论】:

        猜你喜欢
        • 2010-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-13
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 2011-03-05
        相关资源
        最近更新 更多