ios - 从 UIImage 获取数据时内存泄漏

标签 ios iphone

我想从 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循环结束后释放 enter image description here 我做错了什么?

谢谢!

最佳答案

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

关于ios - 从 UIImage 获取数据时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28878297/

相关文章:

ios - 在内部查找字典键和字典数组

ios MapKit 的注释描述在启动时可见,但在点击时不可见

ios - 在 Linux NativeScript 中云构建 IOS

iphone - 如何从第三个 View 直接回到第一个 View ?

iphone - 获取特定标签栏项目的框架

iphone - 在 UICollectionView 上重置滚动

iphone - UIToolbar 项目未显示

c# - MonoTouch native 崩溃调用 CGPDFDictionary.GetArray

ios - 如何使用 swift 在谷歌地图上显示自定义图像

ios - iPad 显示从弹出窗口中选择的图片