I want to have a simple NSSet which is loaded with some NSNumbers and then find out if those numbers are already added in the set or not. When I do this:
NSMutableSet *set = [[NSMutableSet alloc] init];
NSNumber *num1 = [NSNumber numberWithInt:5];
NSNumber *num2 = [NSNumber numberWithInt:5];
[set addObject:num1];
if([set member:num2]){
// something...
}
The problem is that the member always returns nil (if is false), even if those numbers are same. isEqual method returns true. So
if([num1 isEqual:num2]){
// correct
}
works...
In docs I read that member method uses isEqual so I don't know what the problem is...
Thanks for any advice.
When you use NSArray you need to compare the values instead of the objects themselves. Instead of using NSArray, you can use NSMutableIndexSet. This allows you to compare the values with a few less steps.
//during init, add some numbers
NSMutableIndexSet *tSet = [[NSMutableIndexSet alloc] init];
NSUInteger exampleValue = 7;
[tSet addIndex:exampleValue];
exampleValue = 42;
[tSet addIndex:exampleValue];
//...later on
//look to see if numbers are there
if ([tSet containsIndex:7]){
NSLog(@"7 exists!");
}
if ([tSet containsIndex:8]){
NSLog(@"8 exists!");
}
Output: 7 exists!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With