I’ve got a file named ColourUtils.h which contains the following code, I found this which converts hex strings to color.
#import <Foundation/Foundation.h>
@interface ColourUtils : NSObject
+ (UIColor *) colorWithHexString: (NSString *) hex;
@end
@implementation ColourUtils
+ (UIColor *) colorWithHexString: (NSString *) hex
{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];
// strip 0X if it appears
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor grayColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
@end
I’ve got 2 ViewControllers that both need to use this class (for decorating the UI in viewDidLoad). In both .h files, I’ve got this imported : #import "ColourUtils.h".
However, I do get the following error at compile time :
ld: duplicate symbol _OBJC_METACLASS_$_ColourUtils in ...
What is the best way of being able to include this common method into multiple ViewControllers? I’m coming from a Java background whereby a static method and some imports would be fine, but this doesn’t appear to work the same in Objective-C
Don’t put
@implementationparts of a class into a .h file. The .h should only be for the declarations of the class interface that other classes need in order to know what public methods and properties they can use. Create a matching .m file for the part of the class that others don’t need to know about (implementation and private declarations).