gpt4 book ai didi

cocoa - NSExpression 的自定义函数 : unrecognized selector

转载 作者:行者123 更新时间:2023-12-03 16:48:08 25 4
gpt4 key购买 nike

我正在尝试关注 Dave DeLong 博客文章 here 。我们在 NSNumber 上构造一个类别来计算阶乘。它似乎工作正常,但是当我将其包装到 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

我对此有什么不明白的地方?谢谢。

真尴尬。一个愚蠢的错字。抱歉各位。

最佳答案

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

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

关于cocoa - NSExpression 的自定义函数 : unrecognized selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5289920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com