Eslam Hamdy
Eslam Hamdy

Reputation: 7396

Issue in comparing NSString inside NSMutable Array

i write a method that loops through an array of buttons and checks if a string is equal to any of the buttons titles inside the array, but it doesn't work although the string passed to that method equals some strings inside the array, here's my code:

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

What I don't understand is why when I run the program, I get both Inside check Dublicates--->Title Existed and "Inside check Dublicates--->Title Not Existed.

Upvotes: 0

Views: 126

Answers (1)

sch
sch

Reputation: 27536

The code:

if([btnLabel isEqualToString:btn.titleLabel.text])
{
    NSLog(@"Inside check Dublicates--->Title Existed");
} else {
    NSLog(@"Inside check Dublicates--->Title Not Existed");
}

will be executed multiple times because it is in a for loop. That's why you get both logs printed when you run your code.

To test whether self.test contains the string btn.titleLabel.text you should modify your code into:

-(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");
    }
}

Or you can simply use the method -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");
    }
}

* This will work even if btn.titleLabel.text is an NSString.

Upvotes: 2

Related Questions