简体   繁体   中英

sort an NSArray of CLLocation objects

I have an array of CLLocation object. I would like to order this array with the distance to the user current location.

I know that I can calculate the distance between the user's location and each CLLocation object and then order it with this distance. Is there any other solution which doesn't need calculations? Thanks.

You can't get the distance without calculating it. But the calculation is fairly simple, and you have to do it only once in the comparator block.

[array sortUsingComparator:^NSComparisonResult(id o1, id o2) {
    CLLocation *l1 = o1, *l2 = o2;

    CLLocationDistance d1 = [l1 distanceFromLocation:userLocation];
    CLLocationDistance d2 = [l2 distanceFromLocation:userLocation];
    return d1 < d2 ? NSOrderedAscending : d1 > d2 ? NSOrderedDescending : NSOrderedSame;
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM