У меня есть вид карты с аннотациями, и эти аннотации отображают выноску. Когда нажимается кнопка раскрытия информации выноски, она переходит в новый вид.
Мои MKAnnotations - это пользовательский класс, который реализует <MKAnnotation>
. Давайте назовем этот класс MyClass. Они хранятся в NSMutableArray. Во время просмотра этого представления я добавляю каждый объект MyClass в этом массиве к аннотациям представления карты. Используя отладчик, я вижу, что после того, как все это добавление выполнено, порядок [self.MapView annotations] совпадает с NSMutableArray.
Теперь я устанавливаю другую точку останова в mapView: viewForAnnotation: и проверяю порядок 1) моего NSMutableArray и 2) [self.MapView annotations]. Массив, конечно, в том же порядке. Однако порядок аннотаций был зашифрован.
Это было большой проблемой для меня, потому что мне нужно было использовать конкретный экземпляр 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;
}