Ortwin Gentz
Ortwin Gentz

Reputation: 54113

-[UIImage CGImage] returning nil

I'm wondering under which circumstances this code breaks in the second assert. In other words, when can -[UIImage CGImage] return nil? The documentation isn't very telling here.

- (void)setImage:(UIImage *)anImage {
    assert(anImage);
    CGImageRef cgimage = anImage.CGImage;
    assert(cgimage);
}

I'm pretty sure, the UIImage is correct since it's fetched from the app bundle. So far I haven't been able to reproduce the case but I do see some user crash reports.

Upvotes: 3

Views: 3013

Answers (4)

Fabian
Fabian

Reputation: 7003

One more possibility that I've come across in the docs:

If the UIImage object was initialized using a CIImage object, the value of the property is NULL.

Upvotes: 6

Adrian
Adrian

Reputation: 1862

Another possibility is that you have multiple threads accessing the same UIImage object at the same time; this was happening in my code with the same symptom.

That might explain your sporadic crash reports, too, since the access patterns would depend on timing that changes from run to run.

Upvotes: 2

fbrereto
fbrereto

Reputation: 35935

A case where anImage would be non-nil but cgimage would be nil could be contrived as follows:

UIImage* myImage = [[UIImage alloc] initWithCGImage:nil];

As previous answers have indicated there are other ways one could find themselves in such a scenario.

Upvotes: 1

Peter DeWeese
Peter DeWeese

Reputation: 18343

To the best of my knowledge, if the first assert passes(showing that anImage is not nil) it means that it could not load the image. Check to make sure that the image is being copied into your bundle.

Upvotes: 1

Related Questions