0

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.

3
  • This question is confusing. I cleaned up the formatting, but could you restate or elaborate on your problem? Commented Mar 24, 2012 at 19:37
  • if([btnLabel isEqualToString:btn.titleLabel.text]) that statement doesn't work right, although i print the buttons titles and the array is working properly, when i remove btn.titleLabel.text and put a constant string, it works!! Commented Mar 24, 2012 at 19:42
  • Could you log out your self.test array? One of the pointers might not be a UIButton. Commented Mar 24, 2012 at 19:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.