Why isn't my String comparison working in iOS

2019-03-07 05:06发布

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];
}

标签: iphone ios6
1条回答
Evening l夕情丶
2楼-- · 2019-03-07 06:01

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.

查看更多
登录 后发表回答