iosobjective-cnsmutablearraynsfastenumeration

How to implement countByEnumeratingWithState:objects:count: for class that internally use NSMutableArray


I wanted to use

 for (TBL_CardView *cardView in cardsInHand)
    {
        // <#statements#>
    }

TBL_CardView is my custom class, and cardsInHand is just (TBL_CardViewArray*)

So I need to implement countByEnumeratingWithState:objects:count: for my TBL_CardViewArray class.
Is this correct ?

This is my TBL_CardViewArray.h

/**
 *    Keep TBL_CardView in array
 */
@interface TBL_CardViewArray : NSObject

- (TBL_CardView *)drawCard;
- (void)addCard:(TBL_CardView *)card;
- (NSUInteger)cardsRemaining;
- (NSArray*) cardViewArray;

- (TBL_CardView *)drawRandomCard;

@end 

Some important part from TBL_CardViewArray.m

@implementation TBL_CardViewArray
{
    NSMutableArray *_cards;
}

So I am just using TBL_CardViewArrayas s wrapper around NSMutableArray for storing my TBL_CardViewclass.

Question
How to implement countByEnumeratingWithState:objects:count: for my TBL_CardViewArray class.

I did google it, but not found some example that I could reuse easy.
My assumption is that because I am already using NSMutableArray for storing that it is not so complicated, but I can not figure it how ?


Solution

  • Quite simply, forward it to the underlaying NSMutableArray:

    - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])stackbuf count:(NSUInteger)len {
        return [_cards countByEnumeratingWithState:state objects:stackbuf count:len];
    }
    

    You have to avoid mutating the array while it's being enumerated.