views:

149

answers:

1

Hi all,

I'm new to iPhone/Objective-C development. I "jumped the gun" and started reading and implementing some chapters from O'Reilly's iPhone Development. I was following the ebook's code exactly and my code was generating the following error:

CGContextSetFillColorWithColor: invalid context
CGContextFillRects: invalid context
CGContextSetFillColorWithColor: invalid context
CGContextGetShouldSmoothFonts: invalid context

However, when I downloaded the sample code for the same chapter the code is different.

Book Code:

- (void) Render {
    CGContextRef g = UIGraphicsGetCurrentContext();
    //fill background with gray
    CGContextSetFillColorWithColor(g, [UIColor grayColor].CGColor);
    CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
    //draw text in black.
    CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor);
    [@"O'Reilly Rules!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
}

Actual Project Code from the website (works):

- (void) Render {
    [self setNeedsDisplay]; //this sets up a deferred call to drawRect.
}

- (void)drawRect:(CGRect)rect {
    CGContextRef g = UIGraphicsGetCurrentContext();
    //fill background with gray
    CGContextSetFillColorWithColor(g, [UIColor grayColor].CGColor);
    CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
    //draw text in black.
    CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor);
    [@"O'Reilly Rules!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
}

What is it about these lines of code that make the app render correctly?

- (void) Render {
    [self setNeedsDisplay]; //this sets up a deferred call to drawRect.
}

- (void)drawRect:(CGRect)rect {

Thanks in advance for helping out a newbie!

+1  A: 

When you draw things to the screen, you need to have a graphics context (which I'm sure You've read all about), but this is only provided (more or less) when Cocoa calls -drawRect:, so your options are basically only call render in -drawRect:, which doesn't make much sense from the look of what you're trying to do, or have -render tell the system that you want to draw your view, which will cause the system to (eventually) create a graphics context and call your -drawRect:, where the actual drawing code needs to be. Otherwise, there will be no graphics context to draw to, which I believe is what your errors are saying.

(note: system above means as much UIKit as it does OS)

Jared P
Makes sense... thank you Jared!
slythic