【问题标题】:subtracting latitudes with NSNumber type to find distance用 NSNumber 类型减去纬度以找到距离
【发布时间】:2013-11-14 04:59:40
【问题描述】:

我想将两个纬度相减以找到最短距离,但我收到此错误,“指向接口 'NSNumber' 的指针的算术运算,这在非脆弱 ABI 中不是恒定大小”如果我更改- 到 + 我得到一个不同的错误“二进制表达式的无效操作数('NSNumber *' 和 'NSNumber *')”我尝试使用双精度数和许多事物组合,但它不起作用。

NSNumber *userLatitude = [NSNumber numberWithDouble:43.55];//sample

NSArray *listOfCities = [managedObjectContext executeFetchRequest:request error:&error];
    for (CityList *item in listOfCities){
        NSLog(@"latitude is %@",item.latitude);  
        NSNumber *distanceLat =  userLatitude - item.latitude;

然后我会将它们与经度一起插入一个可变数组中并比较距离。使用 CLLocation 的一种可能解决方案是

double distance = [usersCurrentLoc distanceFromLocation:otherLoc];

其中 usersCurrentLoc 和 otherLoc 都是 CLLocation 变量。 我还想单独使用纬度和经度,这样我就可以做一些自定义绘图,而且它们也是单独存储的,所以我想找出正确的数据类型和最有效的解决方案。

item.latitude来自core-data,数据模型类型为double,X-code自动生成CityList类,属性为NSNumber * latitude;

【问题讨论】:

  • 你想找到最短的距离吗?

标签: ios objective-c nsnumber cllocation


【解决方案1】:

如果你想减去两个 NSNumbers,那么就用这个

NSNumber *distanceLat = [NSNumber numberWithFloat:([userLatitude floatValue] - [item.latitude floatValue])];

【讨论】:

    【解决方案2】:

    这个:

    NSNumber *distanceLat =  userLatitude - item.latitude;
    

    需要:

    NSNumber *distanceLat = @([userLatitude doubleValue] - item.latitude);
    

    如果item.latitude 也是NSNumber,那么您也需要调用doubleValue

    NSNumber 是一个对象。你不能对物体做数学运算。您需要使用doubleValue 来获取它的值,然后您需要将结果包装在一个新的NSNumber 实例中。

    顺便说一句-为什么要在这里打扰NSNumber?为什么不这样做:

    double userLatitude = 43.55;
    
    double distanceLat = userLatitude - item.latitude;
    

    【讨论】:

      【解决方案3】:
          CLLocationCoordinate2D newCoordinate = [newLocation coordinate];
          CLLocationCoordinate2D oldCoordinate = [oldLocation coordinate];
      

      CLLocationDistance 米 = [newLocation distanceFromLocation:oldLocation];

      上面的可以用来求两个位置之间的距离

      【讨论】:

        猜你喜欢
        • 2014-02-22
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-24
        • 2018-06-04
        • 1970-01-01
        相关资源
        最近更新 更多