我需要找到NSMutableArray
存储CLLocationCoordinate2D
个对象的20个壁橱存储,并将其添加到另一个数组中。
知道我该怎么办? 谢谢!
答案 0 :(得分:3)
如何使用distanceFromLocation:
?按距离对数组进行排序,取第一个元素。
PS:我假设您实际存储了CLLocation
个实例,因为CLLocationCoordinate2D
是struct
,而不是引用类型。如果您真的以某种方式设法将非对象存储在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]];
}