I have a custom class called card
and I need to create a set of 10 unique cards from an array of cards of a random size. Also, I need include any whitelisted cards first to make sure they are always included.
My problem is cards from the whitelist (and only the whitelist) are potentially duplicated in the set. The cards randomly added are never duplicated, and the count is always correct (10). I can't figure out why isEqual
seems to work sometimes but not always.
Here is where I create the set (randoms
is the array of potential cards to be picked from):
NSMutableSet *randomCards = [NSMutableSet setWithCapacity:10];
[randomCards addObjectsFromArray:whiteListArray];
while ([randomCards count] < 10) {
NSNumber *randomNumber = [NSNumber numberWithInt:(arc4random() % [randoms count])];
[randomCards addObject:[randoms objectAtIndex:[randomNumber intValue]]];
}
I overrode the isEqual
method for my card
class based on another question answered here:
- (BOOL)isEqual:(id)other {
if (other == self)
return YES;
if (!other || ![other isKindOfClass:[self class]])
return NO;
return [self isEqualToCard:other];
}
- (BOOL)isEqualToCard:(Card *)myCard {
if (self == myCard) {
return YES;
}
if ([self cardName] != [myCard cardName] && ![(id)[self cardName] isEqual:[myCard cardName]])
return NO;
return YES;
}
It seems to work perfectly except when I add in the whitelist cards, I can't figure out how I'm ending up with duplicates (but never more than 2 copies).