jannej jannej - 1 year ago 126
Objective-C Question

NSGraphicsContext currentContext returns nil

This is probably a basic newbie question but I have got stuck on this. Trying to set up Core Plot but have some issues.

By looking at the CPTestApp I am trying just to draw anything but I always get an crash in CPTPlatformSpecificFunctions because the NSGraphicContext is nil.

void CPTPushCGContext(CGContextRef newContext)
if ( newContext ) {
if ( !pushedContexts ) {
pushedContexts = [[NSMutableArray alloc] init];
[pushedContexts addObject:[NSGraphicsContext currentContext]];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:newContext flipped:NO]];

Why does [NSGraphicsContext currentContext] returns nil? I would appreciate any hints. The demo app seems to call the init from the application delegate like me.

EDIT, here is my call to Coreplot:


#import <CorePlot/CorePlot.h>

@property (nonatomic, readwrite, strong) IBOutlet CPTGraphHostingView *graphHostView;

ApplicationDeletegate.m (yes, I know you should not have so much code here)

[super awakeFromNib];
[self setupGraph];


CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:graphHostView.bounds];
graph.plotAreaFrame.masksToBorder = NO;
graphHostView.hostedGraph = graph;

[graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
graph.paddingBottom = 30.0f;
graph.paddingLeft = 30.0f;
graph.paddingTop = -1.0f;
graph.paddingRight = -5.0f;

CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = @"Helvetica-Bold";
titleStyle.fontSize = 16.0f;

NSString *title = @"Portfolio Prices: April 23 - 27, 2012";
graph.title = title;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, -16.0f);


Is awakeFromNib too early? Have I missed something?

Answer Source

Maybe there is no currentContext right now? You're setting one, so just modify your code to not push if there isn't one. Verify afterwards that setting it causes currentContext to return the object you set it to.

NSGraphicsContext *ctx = [NSGraphicsContext currentContext];
if(ctx != nil) {
    [pushedContexts addObject: ctx];

Also check your pop to make sure it doesn't do anything dumb if you run out of pushedContexts.