从阵列中找到最近的位置(iOS)

时间:2016-01-22 12:17:34

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

我需要找到NSMutableArray存储CLLocationCoordinate2D个对象的20个壁橱存储,并将其添加到另一个数组中。

知道我该怎么办? 谢谢!

1 个答案:

答案 0 :(得分:3)

如何使用distanceFromLocation:?按距离对数组进行排序,取第一个元素。

PS:我假设您实际存储了CLLocation个实例,因为CLLocationCoordinate2Dstruct,而不是引用类型。如果您真的以某种方式设法将非对象存​​储在CLLocation中,则可以轻松地从纬度和经度构造NSArray个对象。

修改

简单快捷的例子

var a = [CLLocation]() // this would be your actual array
let loc = CLLocation() // this would be your current location
a.sortInPlace { (l1, l2) -> Bool in
    l1.distanceFromLocation(loc) <= l2.distanceFromLocation(loc)
}
let smallest = a.first? // this would be your closest value.

在Objective-C中,NSMutableArray上的相关方法为sortUsingComparator:,如此:

NSMutableArray* a = [NSMutableArray new];
CLLocation* loc = [CLLocation new];
[a sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
// Edit 3: verbose comparator.
    float dist1 =[(CLLocation*)obj1 distanceFromLocation:loc];
    float dist2 = [(CLLocation*)obj2 distanceFromLocation:loc];
    if (dist1 == dist2) {
        return NSOrderedSame;
    }
    else if (dist1 < dist2) {
        return NSOrderedAscending;
    }
    else {
        return NSOrderedDescending;
    }
}];

// Edit 2
CLLocation* smallest = a.firstObject;
    NSMutableArray* closest = [NSMutableArray new];
for (int i = 0; i < 20; i++) {
    [closest addObject:a[i]];
}