2016-02-02 27 views
0

我有一個功能,可以找到最近的store到用戶的位置和排序allStores陣列從最近的到最遠的。 之後,需要將索引0-19(20個儲藏室存儲到用戶的位置)上的商店並將其添加到twentyClosestStores數組。CLLocation distanceFromLocation:returns -1

的問題是:當我嘗試測量location1之間的ditance到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]];