[英]C and Objective-C - Correct way to free an unsigned char pointer
在我的應用程序中,我使用此函數創建一個unsigned char指針:
- (unsigned char*)getRawData
{
// First get the image into your data buffer
CGImageRef image = [self CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), image);
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
return rawData;
}
在另一個類中,我將一個屬性分配給該指針,如下所示:self.bitmapData = [image getRawData];
在這個過程中我可以釋放那個malloc內存嗎? 當我嘗試在dealloc中釋放屬性時,它會給我一個exc_bad_access錯誤。 我覺得我在這里缺少一個基本的c或objective-c概念。 所有幫助表示贊賞。
有一個關於使用malloc /免費在Objective-C的安全商量好了這里 。
只要你正確地釋放()你malloc()的內存, 應該沒有問題。
我個人認為使用NSMutableData或NSMutableArray更容易。 如果您不需要最終性能,我不會直接使用C malloc / free語句。
解決此類問題的一種方法是使用NSMutableData,因此您可以替換
unsigned char *rawData = malloc(height * width * 4);
同
myData = [[NSMutableData alloc] initWithCapacity:height * width * 4];
unsigned char *rawData = myData.mutableBytes;
然后,您可以在解除分配器中釋放myData。
另外你可以這樣做
myData = [NSMutableData dataWithCapacity:height * width * 4];
這將意味着你的myData保持在事件循環的持續時間周圍,你甚至可以更改getRawData方法的返回類型以返回NSMUtableData或NSData,這樣它可以被代碼的其他部分保留,只有當我在代碼中返回原始字節時,如果我知道它將在返回它的對象的生命周期中可用,那樣如果我需要保留數據,我可以保留所有者類。
Apple經常會使用
myData = [[NSMutableData alloc] initWithCapacity:height * width * 4];
unsigned char *rawData = myData.mutableBytes;
模式,然后記錄,如果您需要超出當前自動釋放池周期的字節,您將必須復制它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.