【问题标题】:CLLocation distanceFromLocation: returns -1CLLocation distanceFromLocation:返回 -1
【发布时间】:2016-02-02 08:01:51
【问题描述】:

我有一个函数可以找到离用户位置最近的store,并从最近到最远对allStores 数组进行排序。 之后,它获取索引 0-19 上的商店(20 个壁橱商店到用户的位置)并将其添加到 twentyClosestStores 数组中。

问题是:当我尝试使用distanceFromLocation: 方法测量location1location2 之间的距离时,它返回-1,我不明白为什么。

我的代码:

-(void)sortClosestStores
{
    [self.allStores sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        CLLocation *location1=[[CLLocation alloc] initWithLatitude:((Store*)obj1).geoPoint.latitude longitude:((Store*)obj1).geoPoint.longitude];
        CLLocation *location2=[[CLLocation alloc] initWithLatitude:((Store*)obj2).geoPoint.latitude longitude:((Store*)obj2).geoPoint.longitude];

        float dist1 =[location1 distanceFromLocation:self.locationManager.location]; //Returns -1
        float dist2 = [location2 distanceFromLocation:self.locationManager.location]; //Returns -1
    if (dist1 == dist2) {
        return NSOrderedSame; //Being called because both dist1 and dist 2' value is -1
    }
    else if (dist1 < dist2) {
        return NSOrderedAscending;
    }
    else {
        return NSOrderedDescending;
    }
}];

    if (self.twentyClosestStores==nil) {
        self.twentyClosestStores=[NSMutableArray array];
    }
    self.twentyClosestStores=[NSMutableArray array];

    for (int i = 0; i < 20; i++) {
        [self.twentyClosestStores addObject:[self.allStores objectAtIndex:i]];
    }
}

有人知道为什么它不能正常工作吗?谢谢!

【问题讨论】:

    标签: ios objective-c iphone cocoa-touch cllocation


    【解决方案1】:

    这是NSComparisonResult的枚举

    typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};
    

    -1 用于NSOrderedAscending

    您可以使用

    对数组进行排序
    NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO];
    
    return [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
    

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 2011-07-09
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      相关资源
      最近更新 更多