Search code examples
objective-cmkmapviewnsset

NSSet containsObject Not Working?


I am trying to check if the annotation exists before adding it to array. I can't figure out why [visibleAnnotations containsObject:annotation] always returns False.

MKMapRect mRect = self.locationView.visibleMapRect;
NSSet *visibleAnnotations =[self.locationView annotationsInMapRect:mRect];
NSLog(@"Annotation in Rect %@",visibleAnnotations);

for(NSArray * obj in JSON){
                coordinates.latitude=[[obj valueForKey:@"Latitude"] doubleValue];
                coordinates.longitude=[[obj valueForKey:@"Longitude"] doubleValue];
                NSString *title=[NSString stringWithFormat:@"%@",[obj valueForKey:@"DeviceId"]];
                MapAnnotation *annotation = [[MapAnnotation alloc] initWithTitle:title andCoordinate:coordinates] ;

                NSLog(@"New Annotation %@",annotation);

                if ([visibleAnnotations containsObject:annotation ]) {
                    //[addPins addObject:annotation];
                    NSLog(@"Contains obj");
                }
                [addPins addObject:annotation];
                [annotation release];
            }

Zoomed to only show 1 annotation.

 Annotation in Rect {(<MapAnnotation: 0x1cd80720>)}
 New Annotation <MapAnnotation: 0x1cd79410>

Thanks


Solution

  • If you never change the properties of your MapAnnotation instances once they are created and added to the set, you could override the hash and isEqual: methods for that class to get the behavior you're looking for here.

    NSSet uses those two methods to test objects; if you redefine isEqual: to compare the values contained in the MapAnnontation objects, rather than the identity of the objects themselves, the set will take them to be equal.