【问题标题】:Comparing Strings Not Working - Really Weird比较字符串不起作用 - 真的很奇怪
【发布时间】:2012-11-08 15:28:49
【问题描述】:

无论出于何种原因,我似乎无法弄清楚我的代码无法正确比较两个字符串的原因。我有一个对象数组(包含字符串的配置文件:组),如果它的组与字符串不匹配,我只想删除此配置文件对象。

这就是我所拥有的:

Profile 对象 .h 文件:

@property (nonatomic, copy) NSString *group;

查看阵列并转储不正确配置文件的控制器文件 - 其 .h 文件:

@property (nonatomic, copy) NSString *buttonSelected;

当用户选择一个按钮时设置此 *buttonSelected 代码只是检查发送者标签并分配适当的字符串,如下所示:

[controller setbuttonSelected:@"My Button Has Been Selected"];

当我尝试比较此 buttonSelected 和数组对象时出现问题 - 这是一个具有组属性的配置文件对象:

_profileArray = [xmlParser profiles];

for(int i=0; i<[_profileArray count]; i++){
  NSLog(@"Comparing button: %@ and group: %@", [self buttonSelected], [[_profileArray objectAtIndex:i] group]);

  if([[self buttonSelected] isEqualToString:[[_profileArray objectAtIndex:i] group]]) NSLog(@"Equal");
}

_profileArray 有 3 个对象,其中只有两个对象的组实际上等于 buttonSelected。所以我应该只让系统输出 2“Equal”,但它从不输出“Equal”。

【问题讨论】:

  • 尝试使用其中一种“比较”方法,因为 isEqualToString 也比较 unicode 字符(因为我不知道您如何填写字符串,这可能是问题所在)
  • 我很高兴你提出了这个问题,因为当应用程序读取 XML 文件时确实会在字符串中添加一堆废话 - 我还没弄清楚为什么 - 但我确实经历并清理了这个并将“干净”数据重置回对象。我已经离开了组,所以我回去添加了这个。不过我还是有同样的问题。
  • 它看起来好像即使在通过这样做清理配置文件属性之后: NSString *cleanGroup = [[_profileArray group] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];配置文件信息中仍然有 \n 和一堆空格。为什么会一直这样?
  • 在您的日志行中,您应该检查字符串长度以查看是否遇到隐藏字符或空格。

标签: iphone xcode ios6


【解决方案1】:

您为什么不先将代码分解成更易于调试的部分,然后逐步执行。我会做这样的事情。

NSString *buttonSelectedToCompareAgainst = [self buttonSelected];
NSLog(@"button selected was: %@", buttonSelectedToCompareAgainst);

NSString *profileGroupString;
NSComparisonResult compareResult;
for(Profile *profile in _profileArray){
 NSLog(@"Checking profile: %@", profile);

 profileGroupString = [profile group];
 NSLog(@"Checking profile group: %@", profileGroupString);

 compareResult = [buttonSelectedToCompareAgainst caseInsensitiveCompare:profileGroupString];

 NSLog(@"compare result: %d", compareResult);
}

【讨论】:

【解决方案2】:

想通了。我正在从不同的数组中清理空格等,而不是我用来比较字符串的数组,因此比较永远不会像他们应该的那样出现。清理阵列后,我使用的一切正常。

【讨论】:

    猜你喜欢
    • 2011-09-18
    • 2011-04-07
    • 2011-05-06
    • 1970-01-01
    • 2012-02-24
    • 2014-10-22
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多