Can I use Categories to add class methods?
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.
Yes, you can do this. You're probably not compiling the .m into your project.
You need to add the -ObjC
and -all_load
linker flags in the “Other Linker Flags” setting.
You can, but you should be very careful about adding methods (instance or class) to framework classes. If a method with the same name but different semantics exists anywhere, the effects are undefined. In particular, there could be a private system framework method with the same name, or one might be added by a future OS release, or (worst of all) it could be added by some other bundle, including input managers, colour pickers and other code injection mechanisms. This is an actual problem that does occur in real life.
There are basically two options for fixing this : 1) Don’t Do That (for example, use a standard C function instead), or 2) take steps to reduce the chance of a name conflict using a prefix, like in class names – say, inferis_colorWithHex:
.
You definitely can do it. I'm guessing that there is something wrong within @implementation UIColor(Hex)
Have you import'd the .h file in the class you are calling this method? Also, check if all .m files are in the target.
Hm. After changing the build configuration to release and back to debug, it worked like a charm. Strange.
I know it's late but JiC it helps anyone else tearing their hair out for hours, if you are using CocoaPods in the workspace and have specified the use_frameworks directive this seems to have an effect on whether Category source code in other Frameworks gets loaded.
精彩评论