在ImageContext中创建UIImage进行自动发布

rez*_*a23 1 objective-c uiimage ios

我正在自动释放池内部绘制ImageContext来控制内存占用,并从自动释放池内部返回图像。我在此调用中崩溃,我想知道它是否是由调用函数使用该映像之前在自动释放池中释放该映像引起的。这是我的代码:

-( UIImage *)   imageRepFromShapes
{
    CGRect sheetDisplayView = [ UIScreen mainScreen ].bounds;


    @autoreleasepool {

        UIGraphicsBeginImageContextWithOptions( boundingRect_m.size, NO, 0.0 );

        CGContextRef context = UIGraphicsGetCurrentContext();
        UIGraphicsPushContext(context);
        for ( Shape *shape in arryOfShapes ) {
            [ shape drawShape ];
        }
        UIGraphicsPopContext();

        UIImage     *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个问题是我是否需要在此调用中使用UIGraphicsPushContext和UIGraphicsPopContext并将它们放置在正确的位置。我希望澄清这一点。谢谢你

雷扎

Ian*_*ald 5

将其移至return自动释放池的外部,以确保图像不被丢弃。请执行以下任一操作:

UIImage *image = nil;
@autoreleasepool {
    // ...
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}
return image;
Run Code Online (Sandbox Code Playgroud)

非ARC

UIImage *image = nil;
@autoreleasepool {
    // ...
    image = [UIGraphicsGetImageFromCurrentImageContext() retain];
    UIGraphicsEndImageContext();
}
return [image autorelease];
Run Code Online (Sandbox Code Playgroud)