文本字段包含数学表达式,例如:12+45-6
是否可以将此字符串转换为数字?
我们可以使用谓词设施吗?
NSString *foo = @"((a*b)/c+(d/5))+15";
// dummy predicate that contains our expression
NSPredicate *pred = [NSPredicate predicateWithFormat:[foo stringByAppendingString:@" == 42"]];
NSExpression *exp = [pred leftExpression];
NSNumber *result = [exp expressionValueWithObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:4], @"a",[NSNumber numberWithInt:7], @"b",[NSNumber numberWithInt:2], @"c",[NSNumber numberWithInt:20], @"d",nil]context:nil];
NSLog(@"%@", result); // logs "33"<br/>