NSSet to NSArray casting calling objectAtIndex?

benwad picture benwad · Jan 24, 2012 · Viewed 50.4k times · Source

I'm trying to update an MKMapView by removing all annotations outside the visible area, and adding and removing some annotations inside the visible area. This is my code:

NSSet *visibleAnnotations = [mapView annotationsInMapRect:[mapView visibleMapRect]];
NSSet *allAnnotations = [NSSet setWithArray:[mapView annotations]];
NSMutableSet *nonVisibleAnnotations = [NSMutableSet setWithSet:allAnnotations];
[nonVisibleAnnotations minusSet:visibleAnnotations];
[mapView removeAnnotations:(NSArray *)nonVisibleAnnotations];

NSMutableSet *newAnnotations = [NSMutableSet setWithArray:[_zoomLevels objectAtIndex:clusterLevel]];
[newAnnotations minusSet:visibleAnnotations];
[mapView addAnnotations:(NSArray *)newAnnotations];

This gives me the error -[__NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x13cd40 after the final line in which I cast newAnnotations to an NSArray then add the annotations. Is there something about casting an array to a set that causes this? If so, is there a way round it?

Answer

user529758 picture user529758 · Jan 24, 2012

Despite you're casting NSMutableSet to NSArray, that simple casting won't make NSSet class respond to NSArray's messages. You have to fill an actual NSArray with the elements of the NSSet like this:

NSArray *array = [theNsSet allObjects];