Search code examples
iosios7nsmutableset

isEqualToSet not returning correct value


I am having two NSArray which contains integer values. I want to get common values from both arrays and for this am using NSMutableSet.

Here is my code

`

    NSMutableSet *set1 = [NSMutableSet setWithArray:array1]];

    NSMutableSet *set2 = [NSMutableSet setWithArray:array2];

    if (![set1 isEqualToSet:set2])
    {
        [set2 intersectSet:set1];
        NSArray  *commonArray = [set2  allObjects];
     }

`

Here is the values in array ` array1 ( 2, 3 )

array2 ( 2, 3 ) and values inNSMutableSet` are

` set1 {( 2, 3 )}

set2 {( 2, 3 )} `

As per the condition and values the code will not execute the lines inside the if() condition. But here the if() condition returns wrong value.

Also the [set2 intersectSet:set1]; returns set2 as empty.

Anything wrong with this code.

Please help me to solve this.


Solution

  • There are a couple of things here, one you need to use NSNumber with NSMutableSet, you can't just use standard int.

    NSNumber is effectively an int wrapped in a Class, NSSet requires NSNumber as it deals with objects.

    The code in your if statement will only be executed if (as per your logic above) the two sets are not equal. (! isEqualToSet).

    However isEqualToSet only returns YES if the contents of otherSet are equal to the contents of the receiving set, otherwise NO.

    Finally intersectSet removes from the receiving set each object that isn’t a member of another given set. - yielding the intersection.

    This is important to understand. You want to get common values from the two sets. Whereas Intersect will simply remove the values from one set not found in the other.

    Therefore [set2 intersectSet:set1]; checks what values which are in Set 2 also exist in Set 1.

    Thus after calling [set2 intersectSet:set1]; Set 2 will contain any values that are common between both sets.

    Make sure you are using NSNumber.