0

I'm trying to setup a method in an external class that looks like the following:

myClass.m

- (void)drawSomeStuffInContext:(CGContextRef)context atStartingPoint:(CGPoint *)coords
{
    //draw some stuff (ignoring coords for now)
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 1.0f);
    CGContextMoveToPoint(context, 10, 10); 
    CGContextAddLineToPoint(context, 100, 50);
    CGContextStrokePath(context);
}

viewController.m

- (void)viewDidLoad
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGPoint startCoords = CGPointMake(100.0, 100.0);
    [[myClass alloc] drawSomeStuffInContext:currentContext atStartingPoint:startCoords];
}

The project builds and runs but I receive the following errors in the log with nothing drawn:

[...] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
[...] <Error>: CGContextSetLineWidth: invalid context 0x0
[...] <Error>: CGContextMoveToPoint: invalid context 0x0
[...] <Error>: CGContextAddLineToPoint: invalid context 0x0
[...] <Error>: CGContextDrawPath: invalid context 0x0

I've been scouring the web for a similar question/example with no luck. Are there different/additional parameters that are required? Should I be calling the draw method from somewhere other than viewDidLoad? Advice is much appreciated!

Jesse
  • 2,043
  • 9
  • 28
  • 45

1 Answers1

1

drawRect is not being called (as far as I can tell) this means that the view is not being drawn at all. You ought to call something like [super initWithFrame:frame]; where frame is a CGRect (obviously) in the drawSomeStuffInContext method.

Alternative you could call [[myClass alloc] initWithFrame:frame]; in the viewDidLoad method of viewController.m and store the starting point in a global variable.

prince
  • 506
  • 6
  • 18
  • `myClass` is currently subclassed as an `NSObject` that returns a few calculations for me. Should I move the `drawSomeStuffInContext` to another class subclassed from a `UIView`? I seem to be missing something regarding the implementation of `drawRect` with my current setup. Much thanks for your response! – Jesse Jun 29 '12 at 12:15
  • 1
    If you want to draw anything to the screen then the class has to be a UIView of subclass thereof. So you could just make the class a subclass of a UIView – prince Jun 29 '12 at 12:19
  • I ended up moving everything to `drawRect` which did the trick. I suppose I could've called my method from `drawRect`, too. – Jesse Jun 30 '12 at 11:25