我正在尝试使用NSExpression
计算指数值,如下所示:
NSNumber *number1 = [NSNumber numberWithInteger:2];
NSNumber *number2 = [NSNumber numberWithInteger:4];
NSArray *arrNum=[NSArray arrayWithObjects:number1,number2,nil];
NSExpression *arrayExpression = [NSExpression expressionForConstantValue: arrNum];
NSArray *arrExp=[NSArray arrayWithObject:arrayExpression];
NSExpression* expression =[NSExpression expressionForFunction:@"raise:toPower:" arguments:arrExp];
NSLog(@"powerExp:%@",expression);
int resultSum = [[expression expressionValueWithObject:nil context: nil] intValue];
NSLog(@"resultnum:%f",resultSum);
我收到了错误:
- [__ NSArrayI doubleValue]:无法识别的选择器发送到实例0x7439e60 2012-10-22 16:04:04.034 operator [3958:c07] * 由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [__ NSArrayI doubleValue]:无法识别的选择器发送到实例0x7439e60'
答案 0 :(得分:1)
NSNumber *number1 = [NSNumber numberWithInteger:2];
NSNumber *number2 = [NSNumber numberWithInteger:4];
NSExpression *expr1 = [NSExpression expressionForConstantValue:number1];
NSExpression *expr2 = [NSExpression expressionForConstantValue:number2];
NSArray *exprArgs = [NSArray arrayWithObjects:expr1, expr2, nil];
NSExpression *expression = [NSExpression expressionForFunction:@"raise:toPower:" arguments:exprArgs];
NSLog(@"powerExp:%@",expression);
int resultSum = [[expression expressionValueWithObject:nil context: nil] intValue];
NSLog(@"resultnum:%d",resultSum);
输出:
powerExp:2 ** 4
resultnum:16
答案 1 :(得分:0)
expressionForConstantValue:
需要NSNumber
。您通过NSArray
NSNumber
传递了它。
exp:
函数采用单个数字(n)并返回e ^ n。那是你想要做的吗?或者你的意思是使用raise:toPower:
,它有两个值吗?