Linked Questions

Popular Questions

Iphone Allocation with NSData

Asked by At

I have a method that downloads many images from the internet, then saves them to the device. Here is the code:

-(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:@"",[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;


My problem is that when this runs, the NSData object, data, is allocated but never released, even when the updateImages method is finished. In instruments, each image that is downloaded remains allocated. The total allocations continues to rise as each image is downloaded and eventually there is a out of memory crash. Instruments does not report a leak associated with this object however.

I have tried: [[NSData alloc]initWithContentsOfURL:url] and then releasing it, but that doesn't help.

I have tried putting the autorelease pool only in the updateImages method and only in the downloadChartForDictionary method and neither helps.

I've been stuck on this all day so any help is greatly appreciated

Related Questions