【问题标题】:No Know Class Method in NSString CategoryNSString 类别中的未知类方法
【发布时间】: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


【解决方案1】:

您的代码中有多个错误。

使用实例方法(-)代替静态方法(+)

// INCORRECT. self in a static method points to class object
// + (UIColor *)colorFromHexString

// CORRECT. self is instance method points to instance of class.
- (UIColor *)colorFromHexString

同样在第 1 行分配 hexString 而不是 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];
}

【讨论】:

  • 太好了,谢谢!供参考。在scannerWithString: 中将hexString 作为参数是一个错字。我的意思是有 self 在那里 - 不是它的任何一种方式......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
  • 2013-06-22
  • 2012-01-31
相关资源
最近更新 更多