objective-c - 使用 initWithBitmapDataPlanes 创建 NSImage 时的 Cocoa 内存管理

标签 objective-c cocoa nsimage

我正在从一个 unsigned char * 的 24 位 RGB 数据创建一个 NSImage,如下所示:

NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
                            initWithBitmapDataPlanes:(unsigned char **)&data
                            pixelsWide:gWidth
                            pixelsHigh:gHeight
                            bitsPerSample:8
                            samplesPerPixel:3
                            hasAlpha:NO
                            isPlanar:NO
                            colorSpaceName:NSCalibratedRGBColorSpace
                            bytesPerRow:gWidth*3
                            bitsPerPixel:24];

NSImage *img = [[NSImage alloc] initWithSize:NSMakeSize(gWidth, gHeight)];
[img addRepresentation:bitmap];

我遇到的问题是我稍后要向“数据”写入更多内容,而且我知道 NSImage 不会复制它。我这么说是因为如果我稍后将所有 0 写入我的数据缓冲区,那么图像就会全黑。

我正在为 Objective C 苦苦挣扎,所以如果这是微不足道的,请多多包涵。

如果我制作“数据”的本地副本并且从不释放它,那么一切正常,但显然会泄漏:

unsigned char *copy_of_data = new unsigned char[len];
memcpy(copy_of_data, data, len);

我怎样才能:

(1) 让 initWithBitmapDataPlanes 创建自己的副本并处理释放?

或者 (2) 在图像不再需要数据后,在适当的时候自己释放数据?

最佳答案

planes 参数传递 NULL 可能是最简单的。然后,在分配和初始化图像代表之后,向它询问它的 -bitmapData 并将您的数据复制到其中。文档中建议使用这种方法:

If planes is NULL or an array of NULL pointers, this method allocates enough memory to hold the image described by the other arguments. You can then obtain pointers to this memory (with the getPixel:atX:y: or bitmapData method) and fill in the image data. In this case, the allocated memory will belong to the object and will be freed when it’s freed.

添加了强调。

关于objective-c - 使用 initWithBitmapDataPlanes 创建 NSImage 时的 Cocoa 内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094748/

相关文章:

macos - Swift OS X - 将 .jpeg 保存到 NSImage 数组中

cocoa - 将 NSView 渲染到图像 : cacheDisplayInRect draws transparent areas differently from usual drawRect call

objective-c - 如何让 UITextField 接受焦点而不显示键盘?

macos - 通过cocoa应用程序在safari中打开url

cocoa - 如何在 Mac OS X 10.9 上检测 NaN 传递给 CoreGraphics API 的位置

ios - 如何在 MailCore 中设置撰写邮件的 UID

objective-c - IKImageView 不稳定?

ios - 警告 : Incompatible integer to pointer conversion when using NS_ENUM types

ios - 如何检测用户何时退出 iOS 上的 YouTube 播放器 View ?

Python、iOS - 我可以用 python 编写应用程序的模型吗