Hi i am trying to get an integer value from a NSMutableArray I called programStack which holds all the numbers. This method is an undo method so when I hit undo it erases the last item on the stack and returns the previous option. When i try to get the number the method undoVariable has the right value for string when it is returned but then after when it is displayed I get the wrong value. An example is having 2, 3 on the array. I erase 3 and string shows 2 in UndoVariable and then when I use self.display.text to display it displays 1.57539e-302. Could this be the pointer address? Here is the code.
- (IBAction)undoPressed {
NSString* string = self.display.text;
if(userIsInTheMiddleOfEnteringANumber){
if([self.display.text length])
string = [string substringToIndex:([string length]-1)];
} else {
string = [NSString stringWithFormat:@"%g",[self.brain undoVariable]];
NSLog(@"string is %@", string);
}
self.display.text = string;
}
-(NSString*) undoVariable{
if(self.programStack)
[self.programStack removeLastObject];
if(self.programStack){
NSString* string = @"";
string = [string stringByAppendingString: [self.programStack lastObject]];
NSLog(@"string = %@", string);
NSLog(@"self.display.text = %@", [self.programStack lastObject]);
return string;
}
Your %g format says to treat the given value as a floating point number but
undoVariablesays it returns a NSString. If you really wanted to format it, you’d need %@. However, it’s much simpler to just use the string rather than reformatting it, as in:string = [self.brain undoVariable];.