Search code examples
nsmutablearrayintegernsset

Comparing Sets of Number


I have been trying to use NSSet and NSMutable set to compare a set of numbers using the IntersectSet function. However, I believe I m going against type by using integers. Is there a way to create an NSSet and use the IntersectsSet function for integers. Is there another way of accomplishing this altogether?

Here is a code snippet:

NSSmutableArray *compareRow [[NSMutableArray alloc] init];
NSSet *A_Table = [[NSSet alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12",nil];

//...
//Reading some data from a file.

        //Populate the tables with the third arrays
        [currentHistoryRow addObject:[NSNumber numberWithInt:post1]];
        [currentHistoryRow addObject:[NSNumber numberWithInt:post2]];
        [currentHistoryRow addObject:[NSNumber numberWithInt:post3]];
        [currentHistoryRow addObject:[NSNumber numberWithInt:post4]];
        [currentHistoryRow addObject:[NSNumber numberWithInt:post5]];


        NSSet *compareRow = [[NSSet alloc] initWithArray:currentHistoryRow];

        if ([compareRow intersectsSet:A_Table]) {
            // You'll see this message
            NSLog(@"subset present");
        }

I figure A_Table and compareRow are not of the same type so the condition is never true.


Solution

  • Wrap the integers in NSNumber and then add them to an NSSet. Intersection will work as advertised.

    NSSet *set = [NSSet setWithObjects: @10, @20, nil];
    // etc.