2011-03-13 69 views
2

我试图按照Dave DeLong博客文章here。 我们在NSNumber上构造一个类别来计算阶乘。这似乎很好地工作,但是当我把它包装成一个NSExpression并尝试计算表达式,我得到NSExpression的自定义函数:无法识别的选择器

[NSCFNumber factorial:]: unrecognized selector sent to instance 0x100108d40' 

但在该地址的对象是NSNumber的,它不承认选择。 我很难过。

#import <Foundation/Foundation.h> 

@interface NSNumber (FactorialExpression) 
- (NSNumber *) factorial; 
@end 

@implementation NSNumber (FactorialExpression) 
- (NSNumber *) factorial { 
    double baseValue = [self doubleValue]; 
    double result = tgamma(baseValue+1); 
    return [NSNumber numberWithDouble:result]; 
} 
@end 

int main (int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    NSNumber *n = [NSNumber numberWithDouble:4.2]; 
    NSLog(@"%@ %@", n, [n factorial]); 
    NSLog(@"%p %d", n, [n respondsToSelector:@selector(factorial)]); 

    NSExpression *f = [NSExpression expressionForConstantValue:n]; 
    NSExpression *e = [NSExpression expressionForFunction:f 
              selectorName:@"factorial:" 
               arguments:nil]; 
    NSLog(@"operand %@ %@", [e operand], [[e operand] class]); 
    NSLog(@"operand %@", [e function]); 

    id result = [e expressionValueWithObject:nil context:nil]; 
    //NSLog(@"%@ %@", [result description], [result class]); 
    [pool drain]; 
    return 0; 
} 

2011-03-13 10:09:02.312 test[94896:903] 4.2 32.57809605033135 
2011-03-13 10:09:02.314 test[94896:903] 0x100108d40 1 
2011-03-13 10:09:02.315 test[94896:903] operand 4.2 NSConstantValueExpression 
2011-03-13 10:09:02.316 test[94896:903] operand factorial: 
2011-03-13 10:09:02.316 test[94896:903] -[NSCFNumber factorial:]: unrecognized selector sent to instance 0x100108d40 

我对此不甚了解?谢谢。

这很尴尬。一个愚蠢的错字。对不起大家。

回答

0
NSExpression *e = [NSExpression expressionForFunction:f selectorName:@"factorial:" arguments:nil]; 

选择器名称的末尾不应该有冒号。

0

我有一个类别的问题,但我正在测试一个静态库。所以我不得不为项目添加-ObjC链接器标志。