Reputation: 9062
I have the following category extension of UIColor
:
.h
#import <UIKit/UIKit.h>
@interface UIColor (Colors)
- (NSArray *)reds;
@end
.m
#import "UIColor+Colors.h"
@implementation UIColor (Colors)
- (NSArray *)reds {
return [[NSArray alloc] initWithObjects:[UIColor colorWithRed:1.0/255.0 green:50.0/255.0 blue:98.0/255.0 alpha:1],[UIColor colorWithRed:1.0/255.0f green:37.0f/255.0f blue:75.0f/255.0f alpha:1],[UIColor colorWithRed:1.0/255.0 green:1.0/255.0 blue:52.0/255.0 alpha:1],[UIColor colorWithRed:90.0/255.0 green:13.0/255.0 blue:1.0/255.0 alpha:1],[UIColor colorWithRed:53.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1], nil];
}
@end
Then in a viewcontroller, I'm trying to do something like this: [cell setBackgroundColor:[UIColor reds][0]];
Any idea what I'm doing wrong?
Upvotes: 1
Views: 200
Reputation: 131436
As the others have pointed out, you want to create a class method (method who's definition starts with "+") not an instance method.
However, your code is pretty pointless, since you create and return a new array of UIColor objects every time the class method is called.
That's your only real option in a category since categories can't add instance variables or global variables. You might be able to use associative storage, but I'm not sure how you'd use associative storage from a class method.
Upvotes: 1
Reputation: 1269
I think the most likely problem is that the function reds
needs to be a class method for you to be able to call reds
on the class. So something like this:
.h
@interface UIColor (Colors)
+(NSArray *)reds;
@end
.m
@implementation UIColor (Colors)
+(NSArray *)reds {
return @[[UIColor colorWithRed:1.0/255.0 green:50.0/255.0 blue:98.0/255.0 alpha:1],
[UIColor colorWithRed:1.0/255.0f green:37.0f/255.0f blue:75.0f/255.0f alpha:1],
[UIColor colorWithRed:1.0/255.0 green:1.0/255.0 blue:52.0/255.0 alpha:1],
[UIColor colorWithRed:90.0/255.0 green:13.0/255.0 blue:1.0/255.0 alpha:1],
[UIColor colorWithRed:53.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1]];
}
@end
So basically a +
instead of a -
. If you use -
it is an instance method so you'd have to instantiate an instance of UIColor to call reds
.
Upvotes: 6