Reputation: 2146
I have a category as defined:
#import <Foundation/Foundation.h>
@interface NSString (MyApp)
+ (UIColor *)colorFromHexString;
@end
#import "NSString+MyApp.h"
@implementation NSString (MyApp)
+ (UIColor *)colorFromHexString
{
self = [self stringByReplacingOccurrencesOfString:@"#" withString:@""];
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}
@end
I am getting an error on the line self = [self stringByReplacingOccurrencesOfString:@"#" withString:@""];
that says: "No know class method for selector stringByReplacingOccurrencesOfString:withString" and "cannot assign self in a class method"
.
I am confused as to why I am not able to do this in an NSString Category
. I've seen examples online that do things very similar with 'self' in an NSString Category
so I am not sure why it isn't working here.
Anyone know what I'm doing wrong?
Upvotes: 1
Views: 244
Reputation: 7287
There are multiple errors in your code.
Use the instance method (-) instead of static method (+)
// INCORRECT. self in a static method points to class object
// + (UIColor *)colorFromHexString
// CORRECT. self is instance method points to instance of class.
- (UIColor *)colorFromHexString
Also on line 1 assign hexString
instead of self
.
- (UIColor *)colorFromHexString
{
NSString *hexString = [self stringByReplacingOccurrencesOfString:@"#" withString:@""];
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}
Upvotes: 1