0

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

Brian
  • 3
  • 4
  • 2
    You create a new annotation object and immediately check to see if it's already in your set. There's no way it could be. – Phillip Mills Jun 21 '12 at 18:43

2 Answers2

3

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Perfect, I guess I was trying to do something without fully understanding it. Thank You – Brian Jun 21 '12 at 19:02
1

Because you are creating a new object, and because it is new, it clearly is not in your set.

You need to check each object in the set to see if it is equal to your new object instead.

lnafziger
  • 25,760
  • 8
  • 60
  • 101
  • What? Isn't that what `containObject:` does? – Chuck Jun 21 '12 at 19:02
  • No, it checks to see if it contains this specific object, not an object equivalent to this object. – lnafziger Jun 21 '12 at 19:05
  • 2
    Pretty sure you're mistaken: http://stackoverflow.com/questions/8410606/does-nssets-containsobject-test-for-pointer-equality-or-value-equality – Chuck Jun 22 '12 at 18:51