xcodecomparisonnsset

Casting NSSEt in an conditional statement


Why is this statement always true regardless if the object at index 0 is in the set or not?

smallestNumberSort is an NSMutableArray

smallestNumberSet is an NSSet

if ([smallestNumberSet containsObject:[NSSet setWithObject:[smallestSortComplete objectAtIndex:0]]] == NO)
         [outcome removeAllObjects];

Minimal Code Example

-(void)GoodCoordinates
{
   NSCountedSet *outcome   = [[NSCountedSet alloc] init]; //will contain 4 random plot point between -50 and +50
   NSMutableArray smallestSortComplete = [NSMutableArray alloc] init];
   NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];


   NSMutableArray smallestCoords = [NSMutableArray alloc] initwithObjects: 
      [NSNumber numberWithInt:1]
      [NSNumber numberWithInt:7]
      [NSNumber numberWithInt:-14]
      [NSNumber numberWithInt:10]
      [NSNumber numberWithInt:-21],nil];

 BOOL (inBounds = NO)
   {   

     [smallestSortComplete removeAllObjects];
    smallestSortComplete = [NSMutableArray arrayWithArray:[outcome allObjects]]; 
    [smallestSortComplete sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    
   
               
    if ([smallestCoords containsObject:[smallestSortComplete objectAtIndex:0]] == NO)
       [outcome removeAllObjects];
   else
      inBounds = YES;
}

Solution

  • Let's unnest the code:

    id object = [smallestSortComplete objectAtIndex:0];
    NSSet *set = [NSSet setWithObject:object];
    if ([smallestNumberSet containsObject:set] == NO)
        [outcome removeAllObjects];
    

    The newly created set object is not in smallestNumberSet. Test if object is in smallestNumberSet:

    id object = [smallestSortComplete objectAtIndex:0];
    if ([smallestNumberSet containsObject:object] == NO)
        [outcome removeAllObjects];
    

    or

    if ([smallestNumberSet containsObject:[smallestSortComplete objectAtIndex:0]] == NO)
        [outcome removeAllObjects];