2011-03-13 71 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鏈接器標誌。