LoginSignup
7
7

More than 5 years have passed since last update.

blocksでリソースをスコープに閉じ込める

Last updated at Posted at 2013-03-25

Objective-cを使っていて、
なんらかの寿命をスコープに閉じ込めたい状況ってないでしょうか?
私はあります。

例えばBitmapContextなんかどうでしょうか?

    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 width, height,
                                                 8,
                                                 4 * width,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast);

    CGContextRelease(context); /* これ忘れそう! */

こんな時、例えばこういう方法もあるかな?と思います。

- (void)scopedBitmapContextHeight:(int)height width:(int)width blocks:(void(^)(CGContextRef))blocks
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 width, height,
                                                 8,
                                                 4 * width,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colorSpace);
    colorSpace = NULL;

    if(blocks)
        blocks(context);

    CGContextRelease(context);
}

//使うとき

    [self scopedBitmapContextHeight:100 width:100 blocks:^(CGContextRef context) {
        CGPoint line[] = {{0, 0}, {100, 100}};
        CGContextStrokeLineSegments(context, line, 2);

        CGImageRef imageFromContext = CGBitmapContextCreateImage(context);
        CGImageRelease(imageFromContext);
    }];

うーん、なんか微妙な気もしますが、頭の体操ということでご勘弁を
また、例外のことはまったく考えてません

7
7
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7