Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 372
Inferis Avatar asked Jan 13 '11 21:01

Inferis


People also ask

What is difference between methods and categories?

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.

What is the difference between category and extension?

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.

Which of the following can be achieved with category and extension in Swift?

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.

What is category in IOS?

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.


1 Answers

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

like image 51
Dave DeLong Avatar answered Sep 23 '22 21:09

Dave DeLong