0

I have a base class, written in objective C which for many reasons, is used to get the CGContext when a sub-class needs to draw in drawRect.

-(CGContextRef)fetchContext
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    return context;
}

I now a sub-class written in Swift which needs to do some drawing, so is asking for the CGContext in super....

    override func drawRect(rect: CGRect) {
        // Drawing code
        let bounds = self.bounds;

        let context:CGContextRef = self.fetchContext();

        CGContextSetLineWidth(context, 5.0);
        CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor );

        CGContextBeginPath(context);

        CGContextMoveToPoint(context, 0, 0);
        CGContextAddLineToPoint(context, bounds.size.width, 0);
        CGContextAddLineToPoint(context, bounds.size.width, bounds.size.height);
        CGContextAddLineToPoint(context, 0, bounds.size.height);
        CGContextAddLineToPoint(context, 0, 0);

        CGContextStrokePath(context);

        super.drawRect( rect );
    }

The problem lies in the line

    let context:CGContextRef = self.fetchContext();

This is not compiling with the error:

'Unmanaged<CGContext>' is not convertible to 'CGContextRef'

I'm confused as to why this is. A CGContext is aliased to a CGContextRef in Swift, so I would have thought this would work.

Can someone explain/help?

Fittoburst
  • 2,215
  • 2
  • 21
  • 33
  • Why don't you just skip the obj-c and directly assign like this: `let context = UIGraphicsGetCurrentContext()` – Chris Jan 06 '15 at 19:07
  • 1
    As explained in the answers to the "duplicate", you can *either* annotate the Objective-C function: `-(CGContextRef)fetchContext CF_RETURNS_NOT_RETAINED;` *or* write `self.fetchContext().takeUnretainedValue()` in the Swift code. – Martin R Jan 06 '15 at 19:12
  • Thanks. That explains it. – Fittoburst Jan 07 '15 at 09:56

0 Answers0