我编写了一个循环遍历按钮数组的方法,并检查字符串是否等于数组中的任何按钮标题,但它不起作用,尽管传递给该方法的字符串等于数组中的一些字符串,这是我的代码:
-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
for (UIButton* btn in self.test) {
if([btnLabel isEqualToString:btn.titleLabel.text])
{
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
}
}
// self.test---> it's an array contains group of buttons
// btnLabel----> it's a string passed to that method
我不明白的是,为什么当我运行该程序时,我同时得到 Inside check Dublicates--->Title Existed
和 "Inside check Dublicates--->Title Not存在
。
最佳答案
代码:
if([btnLabel isEqualToString:btn.titleLabel.text])
{
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
会被执行多次,因为它在for
循环中。这就是为什么在运行代码时会打印两个日志的原因。
要测试 self.test
是否包含字符串 btn.titleLabel.text
您应该将代码修改为:
-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
BOOL found = NO;
for (UIButton* btn in self.test) {
if([btnLabel isEqualToString:btn.titleLabel.text]) {
found = YES;
break;
}
}
if (found) {
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
}
或者您可以简单地使用方法-containsObject:
*:
-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
BOOL found = [self.test containsObject:btn.titleLabel.text];
if (found) {
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
}
* 即使 btn.titleLabel.text
是一个 NSString
也能正常工作。
关于objective-c - 在 NSMutableArray 中比较字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9854815/