Konrad Winkowski
Konrad Winkowski

Reputation: 2042

unrecognized selector sent to class when trying to create UIColor

I'm trying to create a custom color out of a hex color code. I have a seperate class called UIColor+Hex, that takes in a hex string and converts it to a color code and returs a UIColor.

UIColor+Hex.h

#import <UIKit/UIKit.h>

@interface UIColor (Hex)

+ (UIColor *)colorWithHexString:(NSString *)hex;

@end

UIColor+Hex.m

#import "UIColor+Hex.h"

@implementation UIColor (Hex)
+ (UIColor *)colorWithHexString:(NSString *)hex
{
    if ([hex length]!=6 && [hex length]!=3)
    {
        return nil;
    }

    NSUInteger digits = [hex length]/3;
    CGFloat maxValue = (digits==1)?15.0:255.0;

    NSUInteger redHex = 0;
    NSUInteger greenHex = 0;
    NSUInteger blueHex = 0;

    sscanf([[hex substringWithRange:NSMakeRange(0, digits)] UTF8String], "%x", &redHex);
    sscanf([[hex substringWithRange:NSMakeRange(digits, digits)] UTF8String], "%x", &greenHex);
    sscanf([[hex substringWithRange:NSMakeRange(2*digits, digits)] UTF8String], "%x", &blueHex);

    CGFloat red = redHex/maxValue;
    CGFloat green = greenHex/maxValue;
    CGFloat blue = blueHex/maxValue;

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

@end

I then have UIColor+Hex.h imported to one of my other classes and make a call to it by:

[self setSelectedfillColor:[UIColor colorWithHexString:@"FF0000"].CGColor];

Whenever I hit this code I get this error...

'NSInvalidArgumentException', reason: '+[UIColor colorWithHexString:]: unrecognized selector sent to class 0x873d60'

I've tried everything I could think of but I still keep getting that error. Anyone have any ideas why this would be happening?

Upvotes: 2

Views: 3532

Answers (3)

Hugh
Hugh

Reputation: 443

Make sure to add UIColor+Hex.m to the Compile Sources list in the Build Phases tab.

The compiler doesn't complain during the build but dies on the selector at runtime.

All too often, it's the missing classes in "Compile Sources" in XCode.

Upvotes: 3

Dcritelli
Dcritelli

Reputation: 820

Tested your category as you posted and it works fine even with the cgcolor property method. Separate those two lines and make sure the problem is not with setSelectedFillColor. Sometimes the debug errors can be misleading.

Upvotes: 2

Dave
Dave

Reputation: 1081

Add -ObjC -all_load to your Other Linker Flags in your project under the Build Settings.

-ObjC allow the static library to use objective-c specific stuffs like kvc or categories.

-all_load solve a bug in gcc/llvm, where -ObjC is not correctly used.

https://developer.apple.com/library/mac/#qa/qa2006/qa1490.html

Upvotes: 7

Related Questions