New to OB-C here. Java programmer by trade.
This is a sample from my view.m file. I have a display that takes some numbers from buttons.
If the display is showing 0, it should clear the 0 first before appending new numbers.
- (IBAction) btn1:(id) sender{[self numPress: (NSString *) @"1"];};
- (IBAction) btnClear:(id) sender{display.text = @"0";};
- (void) numPress : (NSString *) key {
if (display.text == (NSString *) @"0")
display.text = @"";
display.text = [display.text stringByAppendingString: key];
}
- (void) viewDidLoad {
self.display.text = (NSString *) @"0";
}
When I run it as shown, the display sets to ‘0’ then if I hit ‘1’ the display changes to ’01’.
If I press Clear the display resets to ‘0’, then I if hit ‘1’ again, it changes to ‘1’. (the intended result). The first time I pressed ‘1’ the 0 should have been removed.
If I change the viewDidLoad to set the display.text to ‘2’ and change the numPress if statement condition to ‘2’ it works.
- (IBAction) btn1:(id) sender{[self numPress: (NSString *) @"1"];};
- (IBAction) btnClear:(id) sender{display.text = @"0";};
- (void) numPress : (NSString *) key {
if (display.text == (NSString *) @"2")
display.text = @"";
display.text = [display.text stringByAppendingString: key];
}
- (void) viewDidLoad {
self.display.text = (NSString *) @"2";
}
I build then run and the display says ‘2’. I press ‘1’ and the display changes to ‘1’. (clearing the leading ‘2’ as it should).
Can someone help me here, why does ‘2’ work, but ‘0’ fails (but only the fist time), that boggles my mind?
Use
-isEqualToString:instead of comparing pointers (with==).