Search code examples
iosnsstringmkmapviewmkannotationviewmkpinannotationview

Properties of custom Annotation don't visible in delegate methods


I have many custom annotations to whom I gave the property (NameTable and ID). I set this property before AddAnnotation the moment of creation, but these property in the delegate methods are no longer visible. I have multiple annotation associated with elements of tables taken from a database. How can I make them visible in the delegate methods?

 - (void)viewDidLoad
{

     //......

   for(int i=0; i<6; i++){ //loop for create multiple annotations

   AnnotationCustom *annotationIcone =[[AnnotationCustom alloc]initWithCoordinates:coord 
               title:self.myTable.title subTitle:self.myTable.address];

        annotationIcone.nameTable = [NSString stringWithFormat:@"%@", self.myTableName];
        annotationIcone.ID = i+1;

    [self.mapView addAnnotation: annotationIcone;

     //.....
   }

But in the delegate methods:

  (MKAnnotationView *)mapView:(MKMapView *)mapview viewForAnnotation:(id 
   <MKAnnotation>)annotation
    {

     NSLog(@"The name of table is:@"%@", annotation.nameTable);
     //property 'nameTable' not found on object of type '_strong id <MKAnnotation>

     NSLog (@The name of table is:@%@", annotation.ID);
     //property 'ID' not found on object of type '_strong id <MKAnnotation>

         //......
     }

In another method:

    - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{

       NSLog(@"The name of table is %@", self.myTableName);
       // here I get the name of last table open and not the name of table selected


      }

Solution

  • In viewForAnnotation, you need to tell the compiler that the annotation is actually an AnnotationCustom object.

    So you first need to do this:

    AnnotationCustom *annotationCustom = (AnnotationCustom *)annotation;
    

    and then try to access the nameTable property..

    In the didSelectAnnotationView method, if what you want is to get the nameTable value of the annotation selected you need to do the following:

    AnnotationCustom *annotationCustomSelected = (AnnotationCustom *)view.annotation;
    NSLog(@"table name of annotation selected: %@", annotationCustomSelected.nameTable);