简体   繁体   中英

Why does my if statement not work the first time? (Objective-C, Xcode, iPhone)

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 == ).

if ([display.text isEqualToString:@"..."])
    /* ... */ ;

You'll find that you're doing your comparisons wrong

== when used with pointers compares the actual pointer values and not the actual objects.

You should rewrite it to this.

- (IBAction) btn1:(id) sender {[self numPress:@"1"];}; // no need to cast, you have an NSString literal
- (IBAction) btnClear:(id) sender {display.text = @"0";};

- (void) numPress : (NSString *) key {
    if (display.text isEqualToString:@"0")
        display.text = @"";
    display.text =  [display.text stringByAppendingString: key];
}

- (void) viewDidLoad {
    self.display.text = @"0"; // again you have a literal
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM