What's the right memory management pattern for buffer->CGImageRef->UIImage?

后端 未结 4 1860
Happy的楠姐
Happy的楠姐 2021-02-07 14:11

I have a function that takes some bitmap data and returns a UIImage * from it. It looks something like so:

UIImage * makeAnImage() 
{
    unsigned char * pixels          


        
4条回答
  •  灰色年华
    2021-02-07 14:58

    The thumb rule here is "-release* it if you don't need it".

    Because you no longer need provider and imageRef afterwards, you should -release all of them, i.e.

    UIImage * image =  [[UIImage alloc] initWithCGImage:imageRef];
    CGDataProviderRelease(provider);
    CGImageRelease(imageRef);
    return [image autorelease];
    

    pixel is not managed by ref-counting, so you need to tell the CG API to free them for you when necessary. Do this:

    void releasePixels(void *info, const void *data, size_t size) {
       free((void*)data);
    }
    ....
    
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixels, pixelBufferSize, releasePixels);
    

    By the way, you can use +imageWithCGImage: instead of [[[* alloc] initWithCGImage:] autorelease]. Even better, there is +imageWithData: so you don't need to mess with the CG and malloc stuff.

    (*: Except when the retainCount is already supposedly zero from the beginning.)

提交回复
热议问题