【问题标题】:CLLocation becomes nan value for coordinate.latitudeCLLocation 成为坐标的 nan 值。纬度
【发布时间】:2014-08-26 13:19:18
【问题描述】:

我有一个视图控制器,它以模态方式呈现,显示地图视图。所以地图视图使用以下代码可以正常工作,但是有 2 个未使用的变量(长双精度 x1,x2),当我删除它们时,CLLocation 总是在视图控制器第三次出现时返回坐标的 nan 值。 temp1 值将是 nan 第三次,从那时起。

为什么我需要这两个未使用的变量??????,这是我的问题。

- (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];
        }
    }
}

【问题讨论】:

    标签: objective-c mkmapview nsdictionary cllocation mkcoordinateregion


    【解决方案1】:

    temp1 值仅在视图控制器“第三次”出现时才为 NaN 的事实是巧合。

    与实例变量不同,局部变量不会初始化为任何默认值。
    如果您不初始化它们,它们将具有基于当时内存位置的“随机”值。

    通过声明两个“未使用”变量,您只是更改了temp1temp2 的内存位置,这会导致它们的默认值略有不同。

    为避免这种不可预测性,您应该始终初始化局部变量。

    在计算temp1temp2for 循环之前添加这两行:

    temp1 = 0.0;
    temp2 = 0.0;
    


    顺便说一句,从iOS 7开始,你可以避免手动计算中心坐标,只需在添加所有注释后调用showAnnotations即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 1970-01-01
      相关资源
      最近更新 更多