为什么我必须释放这些数据?我是老板吗?

Pro*_*ber 7 memory-management core-graphics objective-c ios

这很奇怪.在技术问答中,Apple说:

void *data = CGBitmapContextGetData (cgctx);
if (data != NULL)
{

    // **** You have a pointer to the image data ****

    // **** Do stuff with the data here ****

}

// When finished, release the context
CGContextRelease(cgctx); 
// Free image data memory for the context
if (data)
{
    free(data);
}
Run Code Online (Sandbox Code Playgroud)

我查阅了CGBitmapContextGetData的文档,并没有提到我在调用它时负责释放数据.已经有CGContextRelease调用来清理上下文.

必须在上下文中额外释放数据有什么意义?它只是指向该数据的指针,对吧?他们为什么free(data)在这里打电话?

puz*_*zle 3

更新:我忽略了阅读整个代码示例。Apple 会分配bitmapDataCreateARGBBitmapContext()不会释放它。这完全没问题,因为上下文仍然需要纳入其中。

然而,bitmapData当他们完成绘图后,必须稍后发布,这正是他们在ManipulateImagePixelData(). 因此,虽然释放通过 get 函数获得的东西是不寻常的,但示例代码是正确的

为了避免释放从 get 函数返回的内容的混乱,人们可能希望将位图数据存储在全局/实例变量中,并free()在完成后存储。


我认为这是代码示例中的错误。该函数的文档没有提及任何特殊内容,因此没有理由说明Get 规则在这里不适用。Quartz 2D 文档还特别重申了 CoreFoundation 内存管理模型适用于 Quartz 2D API。