【问题标题】:Iphone Allocation with NSData使用 NSData 分配 Iphone
【发布时间】:2010-10-08 22:21:40
【问题描述】:

我有一种方法可以从互联网上下载许多图像,然后将它们保存到设备中。代码如下:

-(IBAction) updateImages {
    for (x=0; x<[imagesToUpdate count]; x=x+1) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSMutableDictionary *tempDic = [dic objectForKey:[imagesToUpdate objectAtIndex:x]];
    BOOL newDictionary = [self downloadChartForDictionary:tempDic];

    [pool drain];
    }

}


-(BOOL) downloadChartForDictionary:(NSMutableDictionary *)dictionary {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSMutableDictionary *updatedDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
    NSString *downloadString = [NSString stringWithFormat:@"http://www.photo.com/%@_0001.jpg",[updatedDictionary objectForKey:@"PDFName"]];
    [updatedDictionary setObject:serverAIRAC forKey:@"airac"];
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"MM-dd-y";
    NSString *dateString = [formatter stringFromDate:date];
    [updatedDictionary setObject:dateString forKey:@"date"];
    [formatter release];


    NSURL *url = [NSURL URLWithString:downloadString];
    NSData *data = [NSData dataWithContentsOfURL:url];


    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
    NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];


    NSString *savePath = [NSString stringWithFormat:@"%@/%@^%@_%@.jpg",docsPath,serverAIRAC,[updatedDictionary objectForKey:@"airport"],[updatedDictionary objectForKey:@"PDFName"]];

    BOOL downloaded = [data writeToFile:savePath atomically:YES];

    [pool drain];

    return YES;

}

我的问题是,当它运行时,NSData 对象 data 被分配但从未释放,即使 updateImages 方法完成。在仪器中,下载的每个图像都保持分配状态。随着每个图像的下载,总分配量继续增加,最终出现内存不足的崩溃。 Instruments 不会报告与此对象相关的泄漏。

我试过: [[NSData alloc]initWithContentsOfURL:url] 然后释放它,但这没有帮助。

我尝试将自动释放池仅放在 updateImages 方法中,并且仅放在 downloadChartForDictionary 方法中,但都没有帮助。

我整天都被困在这个问题上,所以非常感谢任何帮助

【问题讨论】:

  • 令人沮丧的是,我还有另一个控制器,它做几乎完全相同的事情,而且效果很好。

标签: iphone ipad memory nsdata


【解决方案1】:

你试过[[[NSData alloc]initWithContentsOfURL:url] autorelease]吗?这会将 NSData 对象放入当前的自动释放池中。直接的 alloc/init 创建仍然需要您的显式管理。

【讨论】:

    【解决方案2】:

    尝试使用具有不同阅读选项的dataWithContentsOfURL:options:error:。我会从NSDataReadingUncached 开始,因为听起来你的数据在你不希望的时候被缓存了。

    【讨论】:

      【解决方案3】:

      这实际上不是问题...由于某种原因,仪器报告了分配情况,但是当我实际运行该应用程序时,它从未崩溃过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-18
        • 1970-01-01
        • 2011-08-26
        • 1970-01-01
        • 1970-01-01
        • 2010-11-18
        • 2011-02-19
        • 2013-11-30
        相关资源
        最近更新 更多