У меня есть вид карты с аннотациями, и эти аннотации отображают выноску. При нажатии кнопки сведений о раскрытии выноски происходит переход в новое представление.
Мои MKAnnotations - это настраиваемый класс, реализующий
. Назовем этот класс MyClass. Они хранятся в NSMutableArray. Во время загрузки этого представления я добавляю каждый объект MyClass в этом массиве к аннотациям представления карты. Используя отладчик, я вижу, что после завершения всего этого добавления порядок [аннотаций self.MapView] совпадает с порядком NSMutableArray.
Теперь я устанавливаю другую точку останова в mapView: viewForAnnotation: и проверяю порядок: 1) мой NSMutableArray и 2) [аннотации self.MapView]. Массив, конечно, находится в том же порядке. Однако порядок аннотаций был изменен.
Это было большой проблемой для меня, потому что мне нужно было использовать конкретный экземпляр MyClass, который пользователь выбрал в следующем представлении. AKA, я хотел посмотреть аннотацию, найти ее индекс, а затем использовать его для получения того же индекса в массиве.
Теперь я понял, что могу просто сохранить аннотацию напрямую (исходя из фона Android, это было очень круто для меня). Тем не менее, я все еще концептуально не понимаю, почему порядок был нарушен. Кто-нибудь может мне помочь? Код ниже:
- (void)viewDidLoad
{
if([fromString isEqualToString:@"FromList"])
self.navigationItem.hidesBackButton = TRUE;
else {
self.navigationItem.rightBarButtonItem = nil;
}
self.array = [MySingleton getArray];
//set up map
//declare latitude and longitude of map center
CLLocationCoordinate2D center;
center.latitude = 45;
center.longitude = 45;
//declare span of map (height and width in degrees)
MKCoordinateSpan span;
span.latitudeDelta = .4;
span.longitudeDelta = .4;
//add center and span to a region,
//adjust the region to fit in the mapview
//and assign to mapview region
MKCoordinateRegion region;
region.center = center;
region.span = span;
MapView.region = [MapView regionThatFits:region];
for(MyClass *t in self.array){
[MapView addAnnotation:t];
}
[super viewDidLoad];
}
//this is the required method implementation for MKMapView annotations
- (MKAnnotationView *) mapView:(MKMapView *)thisMapView
viewForAnnotation:(MyClass *)annotation
{
static NSString *identifier = @"MyIdentifier";
//the result of the call is being cast (MKPinAnnotationView *) to the correct
//view class or else the compiler complains
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[thisMapView
dequeueReusableAnnotationViewWithIdentifier:identifier];
if(annotationView == nil)
{
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
}
annotationView.pinColor = MKPinAnnotationColorGreen;
//pin drops when it first appears
annotationView.animatesDrop=TRUE;
//tapping the pin produces a gray box which shows title and subtitle
annotationView.canShowCallout = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annotationView.rightCalloutAccessoryView = infoButton;
return annotationView;
}