As long as you have only one cycle, it is pretty easy. (BTW: The human math syntax (infix notation) is a little bit weird for computer programming, priority rules and brackets are needed, so some invented another algebraic syntax, the PN or reverse PN.)
When a operator is pressed, you store the operator and the first operand into a ivar. This is a state you enter and usually in GUI programming you try to prevent states. However it is, what users expect from a calculator.
First let us beautify your code with properties and generated ivars.
@interface AppController : NSObject
@property (weak, nonatomic) IBOutlet NSTextField *operandTextField;
@property (weak, nonatomic) IBOutlet NSTextField *resultTextField;
@end
Add properties for the first value and the operation:
@interface AppController : NSObject
@property (weak, nonatomic) IBOutlet NSTextField *operandTextField;
@property (weak, nonatomic) IBOutlet NSTextField *resultTextField;
@property (nonatomic) double operand;
@property (nonatomic) NSString *operator;
@end
Then you need the actions for the operations. Here is an example for one:
@interface AppController : NSObject
@property (weak, nonatomic) IBOutlet NSTextField *operandTextField;
@property (weak, nonatomic) IBOutlet NSTextField *resultTextField;
@property (nonatomic) double operand;
@property (nonatomic) NSString *operator;
- (IBAction)plus:(id)sender;
@end
The next thing you need is to add an action for "operation begin". You can connect it to the text field and make it its "enter" action.
@interface AppController : NSObject
@property (weak, nonatomic) IBOutlet NSTextField *operandTextField;
@property (weak, nonatomic) IBOutlet NSTextField *resultTextField;
@property (nonatomic) double operand;
@property (nonatomic) NSString *operator;
- (IBAction)plus:(id)sender;
- (IBAction)operate:(id)sender;
@end
Okay, done with the interface. Let's go to the implementation:
@implementation AppController
- (IBAction)plus:(id)sender
{
// Store operator
self.operator = [valueTextField doubleValue]; // Some checking?
// Store operation
self.operation = @"+"; // You can use int constant for that, but this is the easy way
}
- (IBAction)operate:(id)sender
{
// Check, whether a operation is already selected
if ([self.operation length]==0)
{
// No: Do nothing
return;
}
// Get the second operand
double operand = [valueTextField doubleValue];
// Do the calculation
double result;
if ([self.operation isEqualToString:@"+"])
{
result = self.operand + operand;
}
else if ([self.operation isEqualToString:@"-"])
{
result = self.operand - operand;
}
…
[self.resultTextField setDoubleValue:result];
self.operation = @"";
// If you do not set this, the next operand will start a new calculation with the first
// operand. Another feature would be to store the result we got and repeatedly perform
// the operation on the last result. But I would change the UI in that case.
}
@end
Typed in Safari.