ios - Objective C - check whether NSString is calculable -
i'm programming calculator in xcode objective c learning (i beginner.). inter alia code using (to calculate 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 user types in 'uncalculable' '6(5+1)' instead of '6 * (5+1)', programme crashes , i'm getting this:
2014-11-01 02:36:10.577 calculator[1515:575020] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: 'unable parse format string "6(5+1) == 1"' *** first throw phone 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 uncaught exception of type nsexception (lldb)
so lastly half hr searching method/function allows first check whether nsstring calculable or not (if necessary) create warning-label or that, didn't find one. there help me?
thanks!
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 not recommended in cocoa. exceptions should used unexpected errors. can utilize math parser 1 https://github.com/davedelong/ddmathparser . sorry english, french.
ios objective-c error-handling nsstring nsexception
No comments:
Post a Comment