NSString isEqualToString不会返回true和无法识别的选择器

时间:2013-03-27 00:27:03

标签: objective-c xcode macos cocoa nsstring

我有一个字符串dummyString需要与100进行比较。这是我的代码

  dummyString = [prefs objectForKey:@"displaySize"];
[self setDisplaySize:dummyString];
NSLog(@"Getting ready to set display controller with value %@", dummyString);


NSLog(@"Tried 1");
if ([dummyString isEqual: @"5"]) {
    NSLog(@"Loaded preferences, display Small");
    displayChanged.selectedSegment = 0;}

NSLog(@"Tried 2");
if ([dummyString isEqual: @"40"]){
    NSLog(@"Loaded preferences, display is Med!");
        displayChanged.selectedSegment = 1;}

NSLog(@"Tried 3");
if ([dummyString isEqualToString:@"100"]){
    NSLog(@"Loaded preferences, display LARGE");
    displayChanged.selectedSegment = 2;}

NSLog(@"Completed trying to get display controller with value %@", dummyString);

这是NSLog

2013-03-26 17:22:49.101 CopyBot[1011:303] Getting ready to set display controller with value 100
 2013-03-26 17:22:49.102 CopyBot[1011:303] Tried 1
 2013-03-26 17:22:49.102 CopyBot[1011:303] Tried 2
 2013-03-26 17:22:49.102 CopyBot[1011:303] Tried 3
 2013-03-26 17:22:49.103 CopyBot[1011:303] -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x64c7
 2013-03-26 17:22:49.103 CopyBot[1011:303] -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x64c7

我尝试了一些声明不同字符串的变体,但似乎无法让它为isEqual或isEqualToString的任何比较输入'if'语句。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:3)

正如您在错误消息[__NSCFNumber isEqualToString:]: unrecognized selector...中看到的那样,问题是__NSCFNumber没有isEqualToString方法。

__NSCFNumber是Cocoa在运行时代表大多数NSNumber的方式。

所以你的问题是dummyString根本不是一个字符串,它是一个NSNumber

答案 1 :(得分:3)

根据您的错误,dummyString不是NSString确实是NSNumber

您可以将字符串@"5"转换为NSNumber,然后比较:

BOOL equal=[dummyString isEqualToNumber:@([@"5" integerValue])];

或者。将dummystring值转换为字符串,然后比较:

BOOL equal=[NSString stringWithFormat:@"%d",[dummyString integerValue]] isEqualToString:@"5"];