Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSSet of NSNumbers - member method is always nil


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.

like image 667
haluzak Avatar asked Nov 08 '11 14:11

haluzak


1 Answers

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!

like image 188
arinmorf Avatar answered Oct 08 '22 08:10

arinmorf