2016-02-02 3 views
0

У меня есть функция, которая находит ближайший store к местоположению пользователя и сортирует массив allStores от ближайшего к самому дальнему. После этого он берет магазины по индексам 0-19 (20 шкафов хранятся в местоположении пользователя) и добавляет их в массив twentyClosestStores.CLLocation distanceFromLocation: возвращает -1

Проблема: когда я пытаюсь измерить ditance между location1 с location2 использованием distanceFromLocation: метода, он возвращает -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]]; 
    } 
} 

Кто-нибудь есть идея, почему это не работает должным образом? Благодаря!

ответ

0

Это перечисление для 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]]; 
Смежные вопросы