我想从 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循环结束后释放 我做错了什么?
谢谢!
最佳答案
您在此代码中没有做任何与内存管理相关的错误。正如@picciano 在他的评论中所说,+imageNamed:
方法缓存它加载的图像,因此使用 +imageWithContentsOfFile:
方法,它不会。还要在实际设备上进行测量,因为在模拟器上测试时内存使用、压力等方面存在差异。
关于ios - 从 UIImage 获取数据时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28878297/