【发布时间】:2016-06-02 14:47:38
【问题描述】:
我有一个定义的类别:
#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
我在self = [self stringByReplacingOccurrencesOfString:@"#" withString:@""]; 行收到一条错误消息:"No know class method for selector stringByReplacingOccurrencesOfString:withString" and "cannot assign self in a class method"。
我很困惑为什么我不能在NSString Category 中做到这一点。我在NSString Category 中看到examples online 与'self' 做的事情非常相似,所以我不确定为什么它在这里不起作用。
有人知道我做错了什么吗?
【问题讨论】:
-
一般来说,您不应该将类别添加到系统类中。如果你这样做,你应该在它们前面加上
_eleven_...以避免冲突。此外,作为 UIColor 上的一个类别(作为类方法),这可能更有意义,因为它有点像颜色工厂方法。
标签: ios objective-c nsstring objective-c-category