我使用NSExpression来计算一个数学字符串,它工作得很好。但是,当输入字符串无效时,我希望有一种捕获错误的方法,例如"3++2“。是否有办法这样做,而不是应用程序终止由于'NSInvalidArgumentException‘。对不起,我对目标-c很陌生。我现在使用的代码是:
NSExpression *exp = [NSExpression expressionWithFormat: string];
NSNumber *result = [exp expressionValueWithObject:nil context:nil];
answer = [result stringValue];发布于 2013-08-24 18:24:41
我认为NSExpression不是这个工作的合适工具。该类是Cocoa谓词系统的一部分,被设计为只接受格式良好的输入。
我建议你找一个合适的数学解析器。我相信GCMathParser是个不错的选择。还有DDMathParser。
如果坚持使用NSExpression,则可以捕获以下异常:
@try {
// the code that potentially raises an NSInvalidArgumentException
} @catch (NSException *exception) {
if ([[exception name] isEqualToString:NSInvalidArgumentException]) {
// your error handling
}
}不过,请注意,这是一种糟糕的做法。Objective中的异常应该仅用于捕获意外的运行时错误。你的例子不合格。
https://stackoverflow.com/questions/18421307
复制相似问题