Can I use Categories to add class methods?

江枫思渺然 提交于 2019-12-10 17:55:15

问题


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.


回答1:


Yes, you can do this. You're probably not compiling the .m into your project.




回答2:


You need to add the -ObjC and -all_load linker flags in the “Other Linker Flags” setting.




回答3:


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:.




回答4:


You definitely can do it. I'm guessing that there is something wrong within @implementation UIColor(Hex)




回答5:


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.




回答6:


Hm. After changing the build configuration to release and back to debug, it worked like a charm. Strange.




回答7:


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.



来源:https://stackoverflow.com/questions/4685497/can-i-use-categories-to-add-class-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!