无法识别的选择器问题

时间:2010-06-05 01:35:20

标签: iphone objective-c cocoa-touch nsstring selector

我很困惑......我有这个函数“colorWithHexString”...当我把它包含在调用它的viewcontroller中时,它工作正常。但是当我将它移动到一个单独的“BSJax”类并使用相同的输入参数调用它时,它会抛出一个无法识别的选择器错误。这是电话:

BSjax *bsjax = [BSjax new];
NSString *hexString = [NSString stringWithString:@"CCCCFF"];
[self.view setBackgroundColor:[bsjax colorWithHexString:hexString]];

我很确定我正在调用函数的方式阻止它作为bsjax方法工作。任何反馈将不胜感激。

BSjax.h包括:

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert;

...和BSjax.m包括:

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6) NSLog(@"colorWithHexString called with parameter < 6 characters in length");

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

    if ([cString length] != 6) NSLog(@"colorWithHexString called with parameter != 6 characters in length");

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

2 个答案:

答案 0 :(得分:6)

您正尝试在实例上调用类方法。

请注意+

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert;

这意味着您只能将方法调用为[ClassName classmethod]

然后在这里,您尝试将该方法用于实例[instanceObject classmethod]

BSjax *bsjax = [BSjax new];
[self.view setBackgroundColor:[bsjax colorWithHexString:hexString]];

尝试将其更改为:

[self.view setBackgroundColor:[BSjax colorWithHexString:hexString]];

这应该让你顺利。

答案 1 :(得分:2)

是否在标题中的@interface BSjax中声明了colorWithHexString,您是否#itrit将该标题放入报告错误的源文件中?

编辑:

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert;

上面的代码(+)声明了一个类方法,这意味着应该使用类名调用它。您正在使用类的实例调用它,而未定义该实例。尝试:

[self.view setBackgroundColor:[BSjax colorWithHexString:hexString]];