Search code examples
objective-ciospointersmkmapviewcllocation

why cant I view a struct value on the previous view controller


I'm pretty new to Objective-C (and C itself) so this is probably really easy, but I'm a bit stuck.

I've got a view controller that requires some input from the user, I have a table view that has a row for a latitude and longitude value. When the user taps that row, it takes them to a new view controller with a map view on it.

I've got a marker for them to drag and pick out their location:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView 
didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState 

In this method I want to update the previous view controller with the new coordinates.

It has a property:

CLLocationCoordinate2D destinationCoordinates;

which I've set as nonatomic, assign and synthesized

My code does this:

NSArray *allControllers = self.navigationController.viewControllers;

EnterDetailsViewController *parent = [allControllers objectAtIndex:([allControllers count] -2)];

if ([parent isKindOfClass:[EnterDetailsViewController class]])
{
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = annotation.coordinate.latitude;
    theCoordinate.longitude =  annotation.coordinate.longitude;

    parent.destinationCoordinates = theCoordinate;

    NSLog(@"Set coord to %@ - %@",
          parent.destinationCoordinates.latitude, 
          parent.destinationCoordinates.latitude);

But the NSLog always crashes with an EXC_BAD_ACCESS - why is this? What core concept am I misunderstanding here?


Solution

  • The definition of CLLocationCoordinate2D is:

    typedef struct {
      CLLocationDegrees latitude;
      CLLocationDegrees longitude;
    } CLLocationCoordinate2D;
    

    Your using %@ to print an object, try instead:

    NSLog(@"Set coord to %f - %f",
          parent.destinationCoordinates.latitude,
          parent.destinationCoordinates.longitude);
    

    Note that CLLocationDegrees is of type double:

    typedef double CLLocationDegrees;