0

I have a Card object, that has a flag isFlipped. I store them in a NSMutableArray. I want to check if two objects in my array have the flag on, and if they do, I remove them. As far as I understand I need to iterate over array, but how do I get another object with a flag?

- (void) checkCards
{
    for (Card *card in cards) {

        if (card.flipped)
        {
            if ( ??? )
            {

            }

        }
    }
}
2
  • Remember where the first one is while you search for the second? Commented Nov 13, 2012 at 1:57
  • Well, first use a regular indexing for loop, so you have a loop index. Then have a "flag 1 index" value that you init to -1. Scan to find the first flag. If "flag 1 index" is -1, change it to your current index and keep scanning. If "flag 1 index" is not -1, you have both flag index values. Commented Nov 13, 2012 at 2:05

2 Answers 2

1

Store the index of the cards that you want to remove in variables and if the value of both the variables are set then just remove the cards. See the following

- (void) checkCards {
    int card1 = -1;
    int card2 = -1;
    for(int i = 0; i < [cards count]; i++) {
        Card *card = [cards objectAtIndex: i];
        if(card.flipped) {
            if(card1 == -1) {
                card1 = i;
            } else {
                card2 = i;
            }

            if(card1 != -1 && card2 != -1) {
                // remove cards
                break;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I would use the NSArray method, indexesOfObjectsPassingTest:. You can use it like this:

    NSIndexSet *indexSet = [cards indexesOfObjectsPassingTest:^BOOL (Card *obj, NSUInteger idx, BOOL *stop) {
        return obj.isFlipped = YES;
    }];
    [cards removeObjectsAtIndexes:indexSet];

This will remove all cards, whose isFlipped is YES, so if there could be more than 2, and you only want to remove 2, then you would have to iterate through the indexSet and stop after removing 2.

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.