我有一个函数,其中我将UIImage
转换为vImage
(用于iOS的Accelerate.framework
中的某些vImage
方法)。
我拥有的方法是:
-(vImage_Buffer)convertImage:(UIImage *)image {
CGImageRef sourceRef = [image CGImage];
NSUInteger sourceWidth = CGImageGetWidth(sourceRef);
NSUInteger sourceHeight = CGImageGetHeight(sourceRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *sourceData = (unsigned char*)calloc(sourceHeight * sourceWidth * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger sourceBytesPerRow = bytesPerPixel * sourceWidth;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(sourceData, sourceWidth, sourceHeight,
bitsPerComponent, sourceBytesPerRow, colorSpace,
kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, sourceWidth, sourceHeight), sourceRef);
CGContextRelease(context);
vImage_Buffer v_image = {
.data = sourceData,
.height = sourceHeight,
.width = sourceWidth,
.rowBytes = sourceBytesPerRow
};
return v_image;
}
我是通过在网上混搭几个代码片段构建的。
我的问题是:我有一个calloc
调用来为sourceData
分配空间。但是,我应该在哪里释放这个内存?
考虑到我可能会多次调用此方法,似乎现在这样会导致内存泄漏。我认为我不会在这里释放它,因为它为我的vImage_Buffer
变量提供了支持.data
。但是,我应该在调用函数中释放它吗?还是将v_image
(或者在调用方法中返回的任何变量)设置为nil
最终会释放calloc
行分配的内存?
有人有任何指针吗?