CGImageRef Memory leak

前端 未结 4 1034
一个人的身影
一个人的身影 2020-12-10 06:35

I\'m having a memory leak when using this custom method which returns a CGImageRef. I can\'t release \"cgImage\" properly because I have to return it. What chould I do ?

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 07:19

    You can autorelease a Core Foundation-compatible object. it just looks a bit wonky. :)

    The GC-safe way is like so:

    CGImageRef image = ...;
    if (image) {
        image = (CGImageRef)[[(id)image retain] autorelease];
        CGImageRelease(image);
    }
    

    The shortcut, which is safe on iOS but no longer safe on the Mac, is this:

    CGImageRef image = ...;
    if (image) {
        image = (CGImageRef)[(id)image autorelease];
    }
    

    Either one will place the image in an autorelease pool and prevent a leak.

提交回复
热议问题