So I built a calculator app in the process of learning Objective-C and Cocoa Touch, but I'm having a strange issue. The user can input an expression including variables and then the calculator evaluates that expression when they hit the Solve button. I've yet to build the mechanism for the user to input their own variables, so right now I set them to some arbitrary numbers.
This is called directly from an IBOutlet if the sender is the Solve button.
Here's the offending bit of code:
If I comment out the second to last line, [brain autorelease];, the program works fine.
But this would result in a memory leak, since a new "brain" object is created every time the user presses Solve, so I would prefer not to do this.
brain.operator and result are both C primitives (doubles), not pointers, so it shouldn't be released when brain.operand is dealloc'd along with the rest of the brain object, correct? double result = brain.operator should create a duplicate?
So why does the program crash after I autorelease?
This is called directly from an IBOutlet if the sender is the Solve button.
Code:
- (void)solve
{
NSMutableDictionary *variableValues = [[NSMutableDictionary alloc] init];
[variableValues setObject:[NSNumber numberWithDouble:2] forKey:[NSString stringWithFormat:@"x"]];
[variableValues setObject:[NSNumber numberWithDouble:3] forKey:[NSString stringWithFormat:@"y"]];
[variableValues setObject:[NSNumber numberWithDouble:4] forKey:[NSString stringWithFormat:@"a"]];
[variableValues setObject:[NSNumber numberWithDouble:5] forKey:[NSString stringWithFormat:@"b"]];
[display setText:[NSString stringWithFormat:@"%g",[CalculatorBrain evaluateExpression:brain.expression usingVariableValues:variableValues]]];
[variableValues autorelease];
return;
}
Code:
+ (double)evaluateExpression:(NSArray *)expression usingVariableValues:(NSDictionary *)variables
{
CalculatorBrain *brain = [[CalculatorBrain alloc] init];
for (id object in expression) {
if ([object isKindOfClass:[NSNumber class]]) {
brain.operand = [object doubleValue];
NSLog(@"%f",brain.operand);
} else if ([object isKindOfClass:[NSString class]]) {
if ([CalculatorBrain isVariable:object]) {
brain.operand = [[variables objectForKey:object] doubleValue];
NSLog(@"%f",brain.operand);
} else {
NSLog(@"%@",object);
[brain performOperation:object];
}
}
}
[brain performOperation:[NSString stringWithFormat:@"="]];
double result = brain.operand;
[brain autorelease];
return result;
}
If I comment out the second to last line, [brain autorelease];, the program works fine.
But this would result in a memory leak, since a new "brain" object is created every time the user presses Solve, so I would prefer not to do this.
brain.operator and result are both C primitives (doubles), not pointers, so it shouldn't be released when brain.operand is dealloc'd along with the rest of the brain object, correct? double result = brain.operator should create a duplicate?
So why does the program crash after I autorelease?