Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-[Not A Type retain]: message sent to deallocated instance

I have converted my app to use ARC.

Before I had the following line of code:

NSArray *colors = [NSArray arrayWithObjects:startColor, endColor, nil];

Since the implicit conversion of a non-Objective-C pointer type to 'id' is disallowed with ARC, I rewrote the line like this:

NSArray *colors = [NSArray arrayWithObjects:(__bridge id)startColor, (__bridge id)endColor, nil];

Everything works fine on the simulator, however on the device the app crashes on the mentioned line with the error message:

-[Not A Type retain]: message sent to deallocated instance

Any ideas how to solve it?

like image 454
Gytis Avatar asked Nov 03 '11 10:11

Gytis


1 Answers

This bridged cast may not work, as hatfinch describes in his answer here, because the CGColorRef returned from -CGColor may not hang around after your last reference to the UIColor that generates it. I thought this was a bug, based on the discussion in this Apple developer forum thread, but it was a misreading of how to manage the lifetime of these CGColorRefs.

One way that this will work is to use the built-in bridging provided by the -CGColor method on UIColor. Rather than saving out your CGColor to a temporary variable as you do above, you should be able to use something like the following:

NSArray *colors = [NSArray arrayWithObjects:(id)[color1 CGColor],
                                            (id)[color2 CGColor], nil];

with color1 and color2 being UIColor instances.

The bridging is taken care of for you by the -CGColor method, according to the "The Compiler Handles CF Objects Returned From Cocoa Methods" section of the Transitioning to ARC Release Notes. The documentation is currently missing the cast to id that I have above, which is required to get this to compile.

I've tested this, and it seems to work in my case, matching what Ben reports in the above-linked Developer Forums thread.

In addition to the above, you can explicitly retain and release the CGColorRefs returned from the -CGColor method and bridge them across in your NSArray, again as hatfinch shows here.

like image 154
Brad Larson Avatar answered Nov 11 '22 08:11

Brad Larson