Is Macro Better Than UIColor for Setting RGB Color? Is Macro Better Than UIColor for Setting RGB Color? xcode xcode

Is Macro Better Than UIColor for Setting RGB Color?


or create a separate category, so you only need to import one .h file:

@interface UIColor (util)+ (UIColor *) colorWithHexString:(NSString *)hex;+ (UIColor *) colorWithHexValue: (NSInteger) hex;@end

and

#import "UIColor-util.h"@implementation UIColor (util)// Create a color using a string with a webcolor// ex. [UIColor colorWithHexString:@"#03047F"]+ (UIColor *) colorWithHexString:(NSString *)hexstr {    NSScanner *scanner;    unsigned int rgbval;    scanner = [NSScanner scannerWithString: hexstr];    [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];    [scanner scanHexInt: &rgbval];    return [UIColor colorWithHexValue: rgbval];}// Create a color using a hex RGB value// ex. [UIColor colorWithHexValue: 0x03047F]+ (UIColor *) colorWithHexValue: (NSInteger) rgbValue {    return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0                           green:((float)((rgbValue & 0xFF00) >> 8))/255.0                            blue:((float)(rgbValue & 0xFF))/255.0                           alpha:1.0];}@end


How about creating your own:

#define RGB(r, g, b) \    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]#define RGBA(r, g, b, a) \    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]

Then use it:

cell.textColor = RGB(0x66, 0x33, 0x33);

Seems simple enough to use, uses hex values for colors and without needing additional calculation overhead.


A middle ground might be your best option. You could define either a regular C or objective-C function to do what your macro is doing now:

// As a C function:UIColor* UIColorFromRGB(NSInteger rgbValue) {    return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0                           green:((float)((rgbValue & 0xFF00) >> 8))/255.0                            blue:((float)(rgbValue & 0xFF))/255.0                           alpha:1.0];}// As an Objective-C function:- (UIColor *)UIColorFromRGB:(NSInteger)rgbValue {return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0                       green:((float)((rgbValue & 0xFF00) >> 8))/255.0                        blue:((float)(rgbValue & 0xFF))/255.0                       alpha:1.0];}

If you decide to stick with the macro, though, you should put parentheses around rgbValue wherever it appears. If I decide to call your macro with:

UIColorFromRGB(0xFF0000 + 0x00CC00 + 0x000099);

you may run into trouble.

The last bit of code is certainly the most readable, but probably the least portable - you can't call it simply from anywhere in your program.

All in all, I'd suggest refactoring your macro into a function and leaving it at that.