比较NSMutableArray中的NSString的问题

时间:2012-03-24 19:30:24

标签: objective-c ios xcode

我编写了一个循环遍历按钮数组的方法,并检查字符串是否等于数组中的任何按钮标题,但它不起作用,尽管传递给该方法的字符串等于数组中的某些字符串,这是我的代码:

-(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 Existed

1 个答案:

答案 0 :(得分:2)

代码:

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.textNSString,这也会有用。