NSMutableSet contains duplicates

I have a custom class called card, and I need to create a set of 10 unique cards from an array of random sizes. In addition, I need to include any whitelists to make sure they are always on.

My problem is the white list cards (and only the white list), which are potentially duplicated in the set. Cards accidentally added are never duplicated, and the calculation is always correct (10). I can’t understand why it isEqualworks sometimes, but not always.

Here I create a set ( randoms- this is an array of potential cards to choose):

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 redefined the method isEqualfor my class cardbased on another question that was asked 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;
}

, , , , , ( 2 ).

+5
1

hash isEqual.

, . Apple:

( isEqual:), -. , .

- :

- (NSUInteger)hash {
    return [[self cardName] hash];
}

, , .

, NSMutableSet, . , , , -. (, , , , hash, , . !)

+15

All Articles