Question 1: how do I have an instance variable make a permanent copy of a value that changes (in this case, self.display.text) instead of a pointer?
Question 2: is my terminology correct in how I stated the problem?
I’m starting up with Obj-c for a few weeks now and I’ve come across this problem. I think part of the problem is that I do not know the correct terminology (and therefore it’s hard to search for a solution). So here it goes:
This is a basic calculator program:
1)User inputs their first number
2)User presses an action (+, -, *, /)
2a) first inputted number is saved; display is reset
3)User inputs second number
4)User presses enter
4a) second inputed number is saved; action is performed on the first and second number
This declares my CalculatorViewController.h
@interface CalculatorViewController : UIViewController
@property double firstNumber, secondNumber, result;
@property int actionType;
@property (weak, nonatomic) IBOutlet UILabel *display;
@property BOOL userIsInTheMiddleOfEnteringANumber;
@end
Implementation here...
// method for when someone clicks an action item on the calculator (such as +, -, *, /)
- (IBAction)pressedAction:(UIButton *)sender {
self.firstNumber = [self.display.text doubleValue];
(action type is set here)
NSLog(@"Action Type: %i", self.actionType);
NSLog(@"FN: %f, SN: %f", self.firstNumber, self.secondNumber);
}
// method for when someone clicks enter (and therefore firstNumber and secondNumber are set
- (IBAction)pressedEnter {
self.secondNumber = [self.display.text doubleValue];
NSLog(@"f: %f, s: %f", self.firstNumber, self.secondNumber);
// should do the given action to the self.firstNumber, self.secondNumber here
}
Here’s my problem: firstNumber is being set as a pointer (terminology?) to the self.display.text (which is the label / output on the screen) instead of being a permanent copy at the time of assignment. Therefore, when the number changes after someone has clicked plus, the firstNumber is being changed as more numbers are being inputted.
Thanks for the help! I really appreciate it!
That cannot be true.
firstNumberis adouble, not a pointer. Ifself.display.textchanges afterwards,firstNumberwill not change.You could test this in code, to see for yourself:
You’ll see that even after
self.display.textchanges,self.firstNumberdoes not.So, your problem is somewhere else. Perhaps your
-pressedAction:method is being called more often than you think it is? In iOS, it’s possible that a button can send more than one action when it is pressed — perhaps you copied-and-pasted a button that was sending-pressedAction:and then you added another action to that button afterwards.