5
votes

I want to add some class methods to UIColor. I've implemented them and everything compiles fine, but at runtime I get the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[UIColor colorWithHex:]: unrecognized selector sent to class 0x8d1d68'

Here's the header file:

@interface UIColor (Hex) 
+ (UIColor*) colorWithHex: (NSUInteger) hex;
@end

Here's the implementation:

#import "UIColor+Hex.h"


@implementation UIColor (Hex)

+ (UIColor*) colorWithHex: (NSUInteger) hex {
    CGFloat red, green, blue, alpha;

    red = ((CGFloat)((hex >> 16) & 0xFF)) / ((CGFloat)0xFF);
    green = ((CGFloat)((hex >> 8) & 0xFF)) / ((CGFloat)0xFF);
    blue = ((CGFloat)((hex >> 0) & 0xFF)) / ((CGFloat)0xFF);
    alpha = hex > 0xFFFFFF ? ((CGFloat)((hex >> 24) & 0xFF)) / ((CGFloat)0xFF) : 1;

    return [UIColor colorWithRed: red green:green blue:blue alpha:alpha];
}
@end

I've found something about adding -all_load to the linker flags, but doing that gives the same result. This is on the iPhone, if it wasn't clear.

7
Have you imported the header file? What does it say in your implementation file?BoltClock

7 Answers

8
votes

Yes, you can do this. You're probably not compiling the .m into your project.

2
votes

You need to add the -ObjC and -all_load linker flags in the “Other Linker Flags” setting.

1
votes

You can, but you should be very careful about adding methods (instance or class) to framework classes. If a method with the same name but different semantics exists anywhere, the effects are undefined. In particular, there could be a private system framework method with the same name, or one might be added by a future OS release, or (worst of all) it could be added by some other bundle, including input managers, colour pickers and other code injection mechanisms. This is an actual problem that does occur in real life.

There are basically two options for fixing this : 1) Don’t Do That (for example, use a standard C function instead), or 2) take steps to reduce the chance of a name conflict using a prefix, like in class names – say, inferis_colorWithHex:.

0
votes

You definitely can do it. I'm guessing that there is something wrong within @implementation UIColor(Hex)

0
votes

Have you import'd the .h file in the class you are calling this method? Also, check if all .m files are in the target.

0
votes

Hm. After changing the build configuration to release and back to debug, it worked like a charm. Strange.

0
votes

I know it's late but JiC it helps anyone else tearing their hair out for hours, if you are using CocoaPods in the workspace and have specified the use_frameworks directive this seems to have an effect on whether Category source code in other Frameworks gets loaded.