使用队列时UIGraphicsGetImageFromCurrentImageContext崩溃

时间:2015-06-18 21:09:11

标签: ios core-graphics grand-central-dispatch

我试图理解使用队列时代码崩溃的方式,但是在使用主线程时工作。这段代码工作正常:

- (void)penMoved:(NSSet *)touches {
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];
    CGPoint midPoint = midpoint(previousPoint, currentPoint);

    CGRect bounds = self.bounds;
    UIGraphicsBeginImageContextWithOptions(bounds.size, YES, [UIScreen mainScreen].scale);

    [path addQuadCurveToPoint:midPoint controlPoint:previousPoint];
    [incrementalImage drawAtPoint:CGPointZero];
    [path stroke];

    previousPoint = currentPoint;

    incrementalImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    [self setNeedsDisplay];
}

但是这个版本的代码在调用incrementalImage = UIGraphicsGetImageFromCurrentImageContext();一段时间后崩溃了。

- (void)penMoved:(NSSet *)touches {
    dispatch_async(drawingQueue, ^{
        UITouch *touch = [touches anyObject];
        CGPoint currentPoint = [touch locationInView:self];
        CGPoint midPoint = midpoint(previousPoint, currentPoint);

        CGRect bounds = self.bounds;
        UIGraphicsBeginImageContextWithOptions(bounds.size, YES, [UIScreen mainScreen].scale);

        [path addQuadCurveToPoint:midPoint controlPoint:previousPoint];
        [incrementalImage drawAtPoint:CGPointZero];
        [path stroke];

        previousPoint = currentPoint;

        incrementalImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        dispatch_async(dispatch_get_main_queue(), ^{
            [self setNeedsDisplay];
        });
    });
}

drawingQueue被定义为这样的ivar:

dispatch_queue_t drawingQueue;

并初始化如下:

drawingQueue = dispatch_queue_create("drawingQueue", NULL);

1 个答案:

答案 0 :(得分:1)

你在谈论接触。你在谈论一个观点。那些东西不是线程安全的。你不能在后台线程上谈论它们。你在两个不同的线程上讨论你的incrementalImage属性。而那只是明显的危险;那里还有其他的属性。