[英]String compare Objective-C
I've been struggling with a simple comparison but I can't get it to work. 我一直在努力进行简单的比较,但无法正常工作。 I´m reading a XML file and I need to compare data from it in order to show the right picture. 我正在读取XML文件,我需要比较其中的数据以显示正确的图片。
http://www.cleaner.se/larm.xml (Example file for parsing) http://www.cleaner.se/larm.xml (用于分析的示例文件)
I have tried things like: 我已经尝试过类似的事情:
if([aLarm.larmClass isEqualToString:@"A"])
NSLog(@"same");
else
NSLog(@"Not same");
If I use: NSLog(aLarm.larmClass);
如果我使用: NSLog(aLarm.larmClass);
console puts it out nicely as it should. 控制台可以很好地将其输出。 What am I doing wrong? 我究竟做错了什么?
You can use the NSString compare: methods. 您可以使用NSString compare:方法。 For example: 例如:
if ([myString caseInsensitiveCompare:@"A"] == NSOrderedSame ) {
NSLog(@"The same");
} else {
NSLog(@"Not the same.");
}
The result is an NSComparisonResult which is just an enum with types NSOrderedSame, NSOrderedAscending and NSOrderedDescending. 结果是一个NSComparisonResult,它只是一个类型为NSOrderedSame,NSOrderedAscending和NSOrderedDescending的枚举。
Check the documentation on the various compare: methods here . 在此处查看有关各种compare:方法的文档。
Of course, if the receiver is actually an NSString, then isEqualToString: should also work. 当然,如果接收方实际上是NSString,则isEqualToString:也应该起作用。 So if you're trying to compare a class name (aLarm.larmClass ??), then you can call: 因此,如果您尝试比较一个类名(aLarm.larmClass ??),则可以调用:
if ([NSStringFromClass([aLarm class]) isEqualToString:@"A"] ) {
NSLog(@"The same");
}
If the larmClass
property is a string, make sure that it is actually one character in length (ie it doesn't have any leading or trailing whitespace that was accidentally included when parsing the XML). 如果larmClass
属性是一个字符串,请确保它实际上是一个字符的长度(即,解析XML时,它没有任何偶然包含的前导或尾随空格)。 If the larmClass
property truly is an NSString
containing the letter 'A' then [aLarm.larmClass isEqualToString:@"A"]
will return YES
. 如果larmClass
属性确实是包含字母'A'的NSString
,则[aLarm.larmClass isEqualToString:@"A"]
将返回YES
。
Do a: 做一个:
NSLog(@"%u, %@", [aLarm.larmClass length], aLarm.larmClass);
and just make sure that it shows “ 1, A
”. 并确保它显示“ 1, A
”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.