LLVM 3.0 compiler error: cast of C pointer type to

2019-07-18 01:17发布

问题:

I am trying to compile old iPhone application project using new LLVM 3.0 compiler. I am getting this error:

Automatic Reference Counting Issue: cast of C pointer type 'CGColorRef' (aka 'struct CGColor *') to Objective-C pointer type 'id' requires a bridged cast [4]

for code:

UIColor *color1, *color2, *color3, *color4;

....

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

This code compiles without problems in older LLVM GCC 4.2 compiler. What is the cause of that? What are the most important things to learn when migrating to the LLVM 3.0 compiler?

回答1:

This is because you're using the compiler's ARC mode (Automatic Reference Counting). For ARC to successfully statically track the reference count of objects that cross the toll-free bridges (Foundation to Cocoa and vice versa), you need to tell it that you've considered the situation. In general, either disable ARC or have a read of The ARC documentation about casts to pick the appropriate solution.

However, here you have a bigger problem. CGColorRef (the type of UIColorInstance.CGColor) is not toll-free bridged to a Cocoa type, and so cannot be safely cast to a id. Why not just store the UIColor?