mRs- / HexColors

HexColors is an extension for UIColor and NSColor to support for creating colors from a hex strings
MIT License
457 stars 102 forks source link

Assert crashes app #11

Closed zackliston closed 9 years ago

zackliston commented 10 years ago

Line 33 in HexColor.m assert(7 == hexString.length || 4 == hexString.length);

This crashes the app if the hexString is not the right length. I'd be nice if it just provided a default color instead of crashing. My solution:

    if (7 != hexString.length && 4 != hexString.length) {
        NSString *defaultHex    = [NSString stringWithFormat:@"0xff"];
        unsigned defaultInt = [[self class] hexValueToUnsigned:defaultHex];

        HXColor *color = [HXColor colorWith8BitRed:defaultInt green:defaultInt blue:defaultInt alpha:1.0];
        return color;
    }

It's not perfect, but I think providing a wrong color is a much better experience than crashing the app. Also, I think error handling belongs inside that library rather than outside of it.

Thanks

mRs- commented 10 years ago

i think it's not the best solution to this way. I can suggest to throw an exception instead of an assert. If you are not really sure if the hex string works (maybe through user input or an API from a third party) it's absolutely the wrong thing to return a working color. It would drive me nuts not knowing why a default color would be returned.

An Exception is a far better way, you can catch it and handle the error in your own implementation (maybe a default color) but it's not a problem in the HexColors class in my opinion.

aporat commented 10 years ago

I'm having the same issue, and as a result, I have to stop using both HexColors and another library that relys on hexcolors. I believe one of my ad provider library contains a built in UIColor category in their complied library, which is also named colorWithHexString.

have you thought about prefixing your category functions with hx_ ?

mRs- commented 10 years ago

yeah i can definitely do that.

mRs- commented 9 years ago

prefixing will be in the next major release. breaking the current implementation