I’m trying to follow a Dave DeLong blog post here.
We construct a category on NSNumber to compute the factorial. It seems to work fine, but when I wrap it up into an NSExpression and try to evaluate the expression, I get
[NSCFNumber factorial:]: unrecognized selector sent to instance 0x100108d40'
But the object at that address is the NSNumber, which does recognize that selector.
I’m stumped.
#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
What am I not understanding about this? Thanks.
It’s embarassing. A stupid typo. Sorry guys.
The selector name should not have a colon at the end.