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.
Instance methods are added to instance of a class, class methods are added to the class itself. A category adds further instance methods that are not available within the class definition itself.
Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.
Use category when you need to want to add any methods to a class whose source code is not available to you OR you want to break down a class into several files depending on its functionality. Use class extensions when you want to add some required methods to your class outside the main interface file.
You use categories to define additional methods of an existing class—even one whose source code is unavailable to you—without subclassing. You typically use a category to add methods to an existing class, such as one defined in the Cocoa frameworks.
Yes, you can do this. You're probably not compiling the .m into your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With