ibm123
ibm123

Reputation: 1254

Memory leak when getting data out of UIImage

I want to extract data from UIImage and do something with that data. I found an memory issue while extracting the data from the UIImage. To isolate the issue i created a new project with just a method that extract data from UIImage.

 -(void)runMemoryValidation:(NSArray*)images  {

    for ( int i=0; i<images.count;  i++) {

        @autoreleasepool {


            NSString* imageName = [images objectAtIndex:i];
            UIImage* image = [UIImage imageNamed:imageName];
            NSUInteger width = 500;//CGImageGetWidth(image.CGImage);
            NSUInteger height = 500;//CGImageGetHeight(image.CGImage);
            //Ref<IntMatrix> matrix(new IntMatrix(width,height));



            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
            unsigned char *data = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
            NSUInteger bytesPerPixel = 4;
            NSUInteger bytesPerRow = bytesPerPixel * width;
            NSUInteger bitsPerComponent = 8;
            CGContextRef context = CGBitmapContextCreate(data, width, height,
                                                         bitsPerComponent, bytesPerRow, colorSpace,
                                                         kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
            CGColorSpaceRelease(colorSpace);

            CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);
            CGContextRelease(context);

            free(data);
        }


     }
       }

I'm sending this method 100 file names and for each loop i load the image and extract the data.

Attached a screenshot, you can see the memory getting higher very quickly and doesn't get released after the for loop finish enter image description here What am i doing wrong ?

Thanks!

Upvotes: 1

Views: 237

Answers (1)

graver
graver

Reputation: 15213

You are not doing anything wrong related to memory management in this code. As @picciano said in his comment +imageNamed: method caches the images it loads, therefore use +imageWithContentsOfFile: method which doesn't. Also do your measures on an actual device, since there's a differece in memory usage, pressure, etc. when testing on the simulator.

Upvotes: 2

Related Questions