I have a view controller which is modally presented that displays a map view. So the map view works correctly with the following code, BUT there are 2 unused variables (long doubles x1, x2) and when I remove them the CLLocation always returns a nan value for the coordinate.latitude the third time the view controller is presented. temp1 value will be nan the third time and from then on.
WHY do I need these 2 unused variables?????, this is my question.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
navigationItemTitle.prompt = name;
if ([mapDict count] > 0)
{
id val = nil;
NSArray *values = [mapDict allValues];
long double x1, x2, temp1, temp2; //x1, x2 unused but necessary
for (int i = 0; i < [mapDict count]; i++)
{
val = [values objectAtIndex:i];
temp1 += ((CLLocation *)val).coordinate.latitude;
temp2 += ((CLLocation *)val).coordinate.longitude;
}
temp1 /= [values count];
temp2 /= [values count];
//NSLog(@"%Lf", temp1);
//NSLog(@"%Lf", temp2);
CLLocationCoordinate2D centerCooordinate = CLLocationCoordinate2DMake(temp1, temp2);
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(centerCooordinate, 10000000, 10000000);
[mapView setRegion:[mapView regionThatFits:region]];
for(id key in mapDict)
{
id value = [mapDict objectForKey:key];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = ((CLLocation *)value).coordinate;
point.title = key;
point.subtitle = [NSString stringWithFormat:@"%f\t%f", point.coordinate.latitude, point.coordinate.longitude];
[mapView addAnnotation:point];
}
}
}
The fact that the temp1
value is NaN only from the "third time" the view controller is presented is a coincidence.
Unlike instance variables, local variables are not initialized to any default values.
If you don't initialize them, they will have "random" values based on whatever is in their memory location at the time.
By declaring two "unused" variables, you're just changing the memory location of temp1
and temp2
which results in them taking slightly different default values.
To avoid this unpredictability, you should always initialize local variables.
Add these two lines before the for
loop that calculates temp1
and temp2
:
temp1 = 0.0;
temp2 = 0.0;
By the way, since iOS 7, you can avoid manually calculating the center coordinate by just calling showAnnotations
after adding all the annotations.