Why isn't my String comparison working in iOS

2019-03-07 05:36发布

问题:

Possible Duplicate:
Understanding NSString comparison in Objective-C

I've used this simple code for several releases of an app, and until iOS 6 the string comparison has worked but now it fails -Why?

if(selectedCell.textLabel.text==@"Font"){
    NSLog(@"going to dofontpicker");
    [self doFontPicker];
}else if(selectedCell.textLabel.text==@"Color"){
    NSLog(@"going to do colorpicker");
    [self doColorPicker];
}

回答1:

Because it never really worked. Comparing strings doesn't work using the == operator, since strings (NSString objects) are pointers - doing a numerical comparison only compares their address, not their contents. You need to write

if ([someString isEqualToString:@"Font"]) {
    // do stuff
}

Edit: I hear you screaming "But it worked! It really worked until iOS 6!" - Nope. It didn't, it was just something accidental.



标签: iphone ios6