【问题标题】:Memory leak when getting data out of UIImage从 UIImage 中获取数据时内存泄漏
【发布时间】:2015-05-06 20:22:03
【问题描述】:

我想从 UIImage 中提取数据并对这些数据做一些事情。 我从 UIImage 中提取数据时发现了内存问题。 为了隔离这个问题,我创建了一个新项目,只使用了一个从 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);
        }


     }
       }

我正在向这个方法发送 100 个文件名,并且对于每个循环,我都会加载图像并提取数据。

附上截图,你可以看到内存很快变大了,for循环结束后没有释放 我做错了什么?

谢谢!

【问题讨论】:

  • 你可能没有做错什么。然而,imageNamed: 中缓存的具体工作方式并没有明确记录。您可能会探索加载这些图像的替代方法。无论如何,那将是我的第一个嫌疑人。

标签: ios iphone


【解决方案1】:

您在此代码中没有做任何与内存管理相关的错误。正如@picciano 在他的评论中所说,+imageNamed: 方法缓存了它加载的图像,因此使用+imageWithContentsOfFile: 方法,它不会。还要在实际设备上进行测量,因为在模拟器上进行测试时,内存使用量、压力等会有所不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多