问题描述
我正在使用NSExpression评估数学字符串,并且效果很好.但是,我想提供一种在输入字符串无效(例如"3 ++ 2")时捕获错误的方法.有没有办法解决此问题,而不是由于"NSInvalidArgumentException"而导致应用程序终止.抱歉,我对Objective-C还是陌生的.我现在使用的代码是:
I am using NSExpression to evaluate a mathematical string and it works great. However I want to have a way of catching an error when the input string is invalid, such as "3++2". Is there a way to go about doing this instead of the application terminating due to 'NSInvalidArgumentException'. Sorry, I am fairly new to objective-c. The code I am using now is:
NSExpression *exp = [NSExpression expressionWithFormat: string];
NSNumber *result = [exp expressionValueWithObject:nil context:nil];
answer = [result stringValue];
推荐答案
我认为NSExpression不是这里工作的正确工具.该类是Cocoa谓词系统的一部分,被设计为仅接受格式正确的输入.
I think NSExpression is not the right tool for the job here. The class is part of the Cocoa predicate system and was designed to only accept well-formatted input.
我建议您寻找合适的数学解析器.我相信 GCMathParser 是一个不错的选择.还有 DDMathParser .
I suggest you look for a proper math parser. I believe GCMathParser is a good choice. There's also DDMathParser.
如果您坚持使用NSExpression,则可以捕获如下异常:
If you insist on using NSExpression, you can catch the exception like this:
@try {
// the code that potentially raises an NSInvalidArgumentException
} @catch (NSException *exception) {
if ([[exception name] isEqualToString:NSInvalidArgumentException]) {
// your error handling
}
}
但是,请注意,这是不好的做法. Objective-C中的异常仅应用于捕获意外的运行时错误.您的示例不符合条件.
Be advised, however, that this is bad practice. Exceptions in Objective-C should only be used to catch unexpected runtime errors. Your example does not qualify.
这篇关于NSExpression捕获无效的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!