219

I've read as many search results I could find on this dreaded problem, unfortunatelly, each one seems to focus on a specific function call.

My problem is that I get the same error from multiple functions, which I am guessing are being called back from functions that I use.

To make matters worse, the actual code is within a custom private framework which is being imported in another project, and as such, debugging isn't as simple?

Can anyone point me to the right direction? I have a feeling I'm calling certain methods wrongly or with bad context, but the output from xcode is not very helpful at this point.

: CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

: CGContextSetStrokeColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

CGContextSaveGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

: CGContextSetFlatness: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

: CGContextAddPath: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

: CGContextDrawPath: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

: CGContextRestoreGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

: CGContextGetBlendMode: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

Those errors may occur when a custom view is presented, or one of its inherited classes. At which point they spawn multiple times, until the keyboard won't provide any input. Touch events are still registered, but system slows down, and eventually may lead to unallocated object errors.

EDIT #1: I do have access to the framework being imported, but I do not see anything weird in the classes which causing the issue.

EDIT #2: I just received an email that iOS 7.1 has been released for developers. I'm curious to see if this goes away, or become worse, or can be solved.

Ælex
  • 14,432
  • 20
  • 88
  • 129
  • 8
    We get this same error in our app - from standard text box on the form. If you tap the text box multiple times while the keyboard is showing you will get this error appearing. –  Dec 09 '13 at 16:38
  • Same here. Sometimes hundreds of these logs, sometimes zero. I thought it was because I'm overriding drawRect: but it seems to be something else. Ignoring it for now. – Krumelur Feb 03 '14 at 09:03
  • 2
    I have just finished the first tutorial on developer.apple.com (copying the code suggested by Apple) and I get this same error. May be if more experienced programmers look at that tutorial they are able to track down the cause of this issue. – Antonio Sesto Feb 03 '14 at 17:13
  • 1
    See below (turn off autolayout in the views where you're using the custom UI elements) – JuJoDi Feb 23 '14 at 02:03
  • 1
    Still happens in 2016 (XCode 7, iOS 9.2), still no apparent harm done. – Hatchmaster J Feb 09 '16 at 10:09

26 Answers26

200

If you're curious what code is causing these logs, you can add a symbolic breakpoint on CGPostError.

Benjohn
  • 13,228
  • 9
  • 65
  • 127
Art Gillespie
  • 8,747
  • 1
  • 37
  • 34
  • 2
    Thanks for the tip about CGPostError. I put a breakpoint on it and it looks like I'm not doing anything to cause this problem. In my case it is happening on the main thread but not in my code. – Paul Heller Nov 06 '13 at 21:56
  • 10
    Votin' this up because, although it's not the solution in this specific case, it WILL often highlight where the fault lies, when it is within the scope of the programmer's own code. – Ash Dec 02 '13 at 20:57
  • 28
    This is a great suggestion. For those who are not familiar with symbolic breakpoints or how to add them in Xcode, here is Apple's doc about it. https://developer.apple.com/library/ios/recipes/xcode_help-breakpoint_navigator/articles/adding_a_symbolic_breakpoint.html – Tony Adams Jan 17 '14 at 15:12
  • This helped me. In my case it highlighted my adding an NSGradient to a view on my OS X app. – Aaron Vegh Mar 09 '14 at 17:13
  • Thank you very much! Doing this got me the stack trace of where it was crashing and I discovered the problem quickly. – Kenny Wyland May 22 '14 at 05:12
  • 1
    It seems I was drawing before setting a frame for a certain view, thank you! :) – Rick van der Linde Aug 04 '14 at 13:04
  • Great tip, with this breakpoint it is very easy to see the origin of the error ! – djleop Feb 27 '15 at 11:06
  • Hi everyone) I have recieved this error, and by debugging with `CGPostError` I saw thas something was wrong with status bar, some stuff with battery offset, and so on. This happens on iOS 9 Simulator during app launch. – Massmaker Oct 13 '15 at 10:28
162

Others will ask you to post the code where you access a core graphics context, but I doubt that's the issue. These invalid context 0x0 error messages are common and easy to reproduce in iOS 7. In fact, I can reproduce the error using storyboard with zero code. I drag a UITextField onto the canvas in IB, run the app, and double tap inside the text field.

In many situations, it's hard for me to take the invalid context 0x0 error messages seriously. I don't know if your situation warrants greater concern (I agree with Rob Napier that it's worth investigating, especially if you are explicitly using a graphics context).

In my own projects, I'm hoping that many of these errors magically disappear some day (but that day did not come with 7.0.3).

Update: After installing Xcode 5.1 and targeting iOS 7.1, I can no longer reproduce the error by double tapping inside an empty text field.

bilobatum
  • 8,918
  • 6
  • 36
  • 50
  • 10
    You're completely correct about this iOS 7 UITextField bug. Be sure to open a radar for it, though (bugreport.apple.com) But don't be too quick to assume that's the issue here. Since it's a custom view, it's worth first investigating @Rob's points. – Rob Napier Oct 25 '13 at 21:31
  • 2
    That is happening to me.. I drop a uitextfield on IB, get that error and keyboard doesn't appear.. is there some solution?? Thanks – Frade Nov 06 '13 at 16:00
  • @Frade For me, the keyboard appears and the app runs normally despite the stern error message. So you may have an additional problem. – bilobatum Nov 12 '13 at 21:56
  • @bilobatum Think not. I get the same message, in the same scenario. Fortunately only happens on simulator. Thanks – Frade Nov 13 '13 at 15:48
  • 3
    I also have the same issue. It also only happens in the simulator, but I noticed that, when I'm getting the bug, I can't use the Mac keyboard to type in the simulator and I have to use the onscreen keyboard, which is very frustrating. In my app I am not using any custom views, so I never manually create or use a CG context. –  Nov 24 '13 at 03:43
  • 1
    Thank goodness for that, I thought it was my app that was at fault! You're completely right though; it was double-clicking in a text field that was causing this error for me too. – Ash Dec 02 '13 at 20:55
  • Quite possibly the most scary error message for the least amount of code changes! – fatuhoku Apr 17 '14 at 15:49
42

These sorts of errors are historically the result of calling Core Graphics functions when not within a context that is established within drawRect or between calls like UIGraphicsBeginImageContext and UIGraphicsEndImageContext (or other UIKit functions like that which begin and end a context).

Having said that, though, bilobatum is correct that this particular sequence of errors can be a result of that iOS 7 bug he references in his answer. If not seeing these errors in your iOS6 targets, or if after a quick scan of this private framework you don't find any suspect Core Graphics calls, it may just be this iOS 7 bug. Good catch, bilobatum!

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • I do have a view in the private framework which calls drawRect. Whereas I'm not directly calling any of the mentioned methods, my only assumption is that the code in that class is somehow related. Yet, like I mentioned, everything runs smoothly under previous iOS'es. – Ælex Nov 07 '13 at 20:15
  • For the sake of completion (this is the top google result) , I'd like to note that the cryptic error is unchanged on OSX 10.11.3 - and caused, as Rob says, by having a drawing function outside drawRect or another context-related function. – green_knight Mar 07 '16 at 21:37
26
UIGraphicsBeginImageContext( size );
CGContextRef context = UIGraphicsGetCurrentContext();

make sure the size.width or size.height is not 0,

you can add symbol breakpoint to CGPostError to check

andrewchan2022
  • 4,953
  • 45
  • 48
  • so… adding a symbolic breakpoint at CGPostError, how can one look at size at that point? – Cris Mar 25 '14 at 17:38
  • you can view the function call stack in "show the debug navigation" by command+6. then you click on the tree, then you can go back to your function to view the variable. – andrewchan2022 Mar 31 '14 at 08:00
  • Yes, I was passing imageview to make that imagview circular, But, Found that Its size was zero. Finally got resolved after 2 days :D. – JiteshW Sep 14 '15 at 06:30
19

I had this problem with a simple UITextField (keyboard not showing up and many different invalid context error messages on the console). I just find a workaround by looking to another problem on SO: Cannot find executable for CFBundle CertUIFramework.axbundle

Just do:

click on iOS Simulator > Reset Content and Settings... and run again.

The problem shouldn't be there anymore

Community
  • 1
  • 1
Kevin Delord
  • 2,498
  • 24
  • 22
16

In my case i've got these errors in this code:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
UIBezierPath *path;

path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(size*2, 0)];
[path addLineToPoint:CGPointMake(size, size*2)];
[path closePath];
[path fill];

shapeLayer.path = path.CGPath;
shapeLayer.strokeColor = [[UIColor blackColor] CGColor];
shapeLayer.fillColor = color;
shapeLayer.lineWidth = width;

[self addSublayer:shapeLayer];

after some thoughts and test I detect the problem - it was this call:

[path fill];

as I detect - in my code this call is not necessary, because of filling will be done by other way - so I simply remove it.

Denis Kozhukhov
  • 1,205
  • 8
  • 16
5

I had this same issue and I forgot to import QuartzCore/QuartzCore.h, This solved my issue with these errors.

    #import <QuartzCore/QuartzCore.h>
David Roop
  • 184
  • 2
  • 11
5

Straight Answer : The problem is because you have used Core graphics elements like CGContext etc in other than - (void)drawRect:(CGRect)rect this method.

Now kindly move your code to this method. And it will strop giving you warnings/Errors.

4

I was getting this error because I was using a UIColor object as an attribute in an NSAttributedString dictionary that was being used in a CATextLayer object. I changed the dictionary to hold a CGColorRef and the error went away.

[wordAttributes setObject:(id)[UIColor whiteColor].CGColor forKey:(NSString*)kCTForegroundColorAttributeName];
Collin
  • 6,720
  • 4
  • 26
  • 29
2

I have had cases where the context returned from UIGraphicsGetCurrentContext() is NULL, and if you try using it for anything this message appears. It is the view's responsibility to push a context using UIGraphicsPushContext prior to calling drawRect:, if you call drawRect: directly instead of [view setNeedsDisplay] you risk the context not being set yet. My hunch is that prior to iOS 7 the context was pushed for the view on init, and now on iOS 7 the context isn't pushed until the first time drawRect: is about to be called. I suspect some UIKit code is calling drawRect: directly and this is why there are issues with some code even when no custom drawing is being done.

Solutions (if doing custom drawing):

  1. Don't call drawRect: directly, use [view setNeedsDisplay] or if you need immediate drawing use [view.layer draw]
  2. In your drawRect: get the context but don't use it outside the body of this if statement if (context) {<do drawing here>}
jamone
  • 17,253
  • 17
  • 63
  • 98
2

Turning off autolayout in the affected view causes this error to go away in some cases where you're placing and moving UI elements (especially custom ones which are drawn programmatically) within a view. I was using JVFloatLabeledTextField when I discovered this symptom.

JuJoDi
  • 14,627
  • 23
  • 80
  • 126
2

In some cases you may need to include the line #import <QuartzCore/QuartzCore.h>.

Andreas
  • 5,393
  • 9
  • 44
  • 53
Nagarjun
  • 6,557
  • 5
  • 33
  • 51
2

I got this error in the drawInContext(..) method of my custom CALayer implementation. UIBezierPath tries to use the UIGraphicsGetCurrentContext() which is nil by default in a custom layer. The online documentation explains this very clearly -

If you are not using a UIView object to do your drawing, however, you must push a valid context onto the stack manually using the UIGraphicsPushContext function.

Here's the code that finally worked with my comments inline (Swift code, but the solution is the same regardless)

override func drawInContext(ctx: CGContext!) {  
    var path = UIBezierPath()

    // 1. Make sure you push the CGContext that was first passed into you.
    UIGraphicsPushContext(ctx)
    path.moveToPoint(CGPoint(x: 0, y: 0))
    path.addLineToPoint(CGPoint(x: 150, y: 150))
    var lineColor = UIColor.blueColor()
    lineColor.setStroke()
    path.lineWidth = 2
    path.stroke(
    // 2. Pop the context after you are done.
    UIGraphicsPopContext()
}
inder
  • 943
  • 11
  • 15
2

In my case I was having this warning when creating a resible image with cap insets. The problem was that I wasn't leaving at least 1 pixel in the "uncapped" area.

    UIImage *image = [UIImage imageNamed:@"name"];
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(20, 10, 20, 10);  //Problem here if the width is 20 or the height is 40
    image = [image resizableImageWithCapInsets:edgeInsets];
balkoth
  • 698
  • 7
  • 11
  • 1
    Had exactly the same issue. Apparently you have to leave at least 1 point of area where the image can stretch – ribeto May 11 '15 at 21:18
1

I was creating UIImage from context using below code:

    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, (CGRect){.size = size});

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

Thus I was getting the error.

So I removed the Derived Data content, restarted my XCode. And it worked.

Meet
  • 4,904
  • 3
  • 24
  • 39
1

I have the same problem. In my project, i have try to create a textField and add it to my pdf file. Old Code:

- (void) drawInContext:(CGContextRef)context {
    //Otherwise we're upside-down
    CGContextSetTextMatrix(context, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));

    CGContextSetTextDrawingMode(context, kCGTextFill); // This is the default
    [[UIColor blackColor] setFill]; // ***This is the problem ***

    CGFloat x = self.rect.origin.x;
    CGFloat y = self.rect.origin.y + self.font.pointSize;
    [self.text drawAtPoint:CGPointMake(x, y)
            withAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:12]}];
}

After solved this problem,the code changed :

old:[[UIColor blackColor] setFill]; 

new:CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);

I found the solution at UIColor SetFill doesn't work. And Thanks the helper.

Community
  • 1
  • 1
Kate
  • 1,107
  • 8
  • 7
1

I got the error with the code

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:pointA];
[path addLineToPoint:pointB];
[path addLineToPoint:pointC];
[[UIColor colorWithHexString:@"EFEFEF"] set];
[path fill];
[path closePath];

CAShapeLayer *triangle = [CAShapeLayer layer];
triangle.fillColor = [UIColor colorWithHexString:@"EFEFEF"].CGColor;
triangle.path = path.CGPath;

return triangle;

and after removed the code

[[UIColor colorWithHexString:@"EFEFEF"] set];
[path fill];

The world became silent

sKhan
  • 9,694
  • 16
  • 55
  • 53
wossoneri
  • 317
  • 2
  • 11
0

I had this problem in a UITextField when I held the touch over a blank field with just placeholder text. I used the following work-around to eliminate blank fields:

-(void)textFieldDidBeginEditing:(UITextField *)textField{

        textField.text=[@" " stringByAppendingString:textField.text];

        //other stuff here
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField{

         if(textField.text.length>0){
             if([[textField.text substringToIndex:1] isEqualToString:@" "])
                 textField.text=[textField.text substringFromIndex:1];
         }
         //  other stuff here
}
Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
Peter B. Kramer
  • 16,385
  • 1
  • 16
  • 20
0

For me, the answer was that I was unnecessarily releasing the graphics context in drawRect:. Throwing a symbolic breakpoint on CGPostError pointed me to the culprit.

Taylor Halliday
  • 640
  • 1
  • 8
  • 19
0

Got this error as I had set

textfield.delegate = self

Without implementing any of the delegate routines. Removing that line solved the problem for me

Daniel Åkesson
  • 1,330
  • 1
  • 12
  • 21
0

For me I was getting this error because I was releasing the the CGContextRef as shown below:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    // DRAW BACKGROUND CIRCLE
    CGContextSetFillColorWithColor(context, [[UIColor gray] colorWithAlphaComponent:0.6].CGColor);
    CGContextFillEllipseInRect(context, rect);

//    CGContextRelease(context);
}

Removing the release solved the issue

Kyle Redfearn
  • 2,172
  • 16
  • 34
0

I got it when I mistyped the image name in activityImage method in UIActivity subclass

- (UIImage *)activityImage
{
    return [UIImage imageNamed:@"img.png"];
}

Typing the right image solved it for me.

Saleh Albuga
  • 448
  • 5
  • 11
0

Uninstall the app from simulator and run again

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Nagarjun
  • 6,557
  • 5
  • 33
  • 51
0

Like others whom have commented here I was getting this warning when I did any of the following:

On a blank text field: Double tapping, touch and hold, long single tap.

This seems to only affect iOS 7.0.3

I discovered a work around, the warning will not be triggered if your pasteboard is not NULL.

So I did the following in textFieldDidBeginEditing:

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (pasteboard.string.length == 0) {

        pasteboard.string = @" ";

    }
}

I tested this out in simulator for iOS 7.0.3 on the iphone 4s, 5 and 5s and no longer receive the warning. I also tested this out in simulator for iOS 8 on the iphone 6 and 6 plus but I don't believe iOS 8 is affected.

Went through two days of frustration before discovering this work around so I really hope my answer helps those of you who are having the same issue.

RS-232
  • 1
  • 2
0

If the error occurs when you are using UIBezierPath and set color for stroke or fill, put the set color code in drawRect function rather than other places.

Chuyang
  • 71
  • 1
  • 7
0

This is hacky but it worked for me.

I set up the UIImageView in the UITableViewCell's init, give it a size and constraints.

Then in my view controller's cellForRowAtIndexPath I do this:

let img = PFImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
img.setImage(withFile: nil, defaultText: message.senderUsername)
cell.profileImageView?.image = img.image

And that avoids the error, then below that in the function I set the actual image for that UIImageView. The code above is a good default

Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151