Search code examples
iosobjective-cerror-handlingnsstringnsexception

Objective C - check whether NSString is calculable


I'm programming a calculator in Xcode with Objective C for learning (I am a beginner.). This is inter alia the code I am using (to calculate a NSString).

- (IBAction)resultButtonPressed:(id)sender {

NSExpression *expression = [NSExpression expressionWithFormat:label_result.text];

label_result.text = [NSString stringWithFormat:@"%@", [expression expressionValueWithObject:nil context:nil]];

}

The problem is, that, whenever a user types in something 'uncalculable' like '6(5+1)' instead of '6 * (5+1)', the program crashes and I'm getting this:

2014-11-01 02:36:10.577 The Calculator[1515:575020] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "6(5+1) == 1"'
*** First throw call stack:
(0x18672de48 0x196e280e4 0x18753ad98 0x187538e2c 0x18764b128 0x18764b0c4 0x100062244 0x18af110f8 0x18aefa22c 0x18af10a94 0x18af10720 0x18af09c74 0x18aedd38c 0x18b17c1b4 0x18aedb8f4 0x1866e60e8 0x1866e538c 0x1866e343c 0x1866111f4 0x18f7a75a4 0x18af42784 0x10006286c 0x197496a08)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

So for the last half hour I was searching for a method/function which allows you to first check whether the NSString is calculable or not so that I could (if necessary) create a warning-label or something like that, but I didn't find one. Is there anyone who could help me?

Thanks!


Solution

  • try that!

    @try {
    NSExpression *expression = [NSExpression expressionWithFormat:label_result.text];
    label_result.text = [NSString stringWithFormat:@"%@", [expression expressionValueWithObject:nil context:nil]];
    } @catch (NSException *exception) {
    if ([[exception name] isEqualToString:NSInvalidArgumentException]) {
    label_result.text = @"Invalid Expression";
    }
    

    Note: Try/catching exception like that are not really recommended in Cocoa. Exceptions should be used to unexpected errors. You can also use a Math Parser like this one https://github.com/davedelong/DDMathParser . Sorry for my english, I am french.