我仍在学习目标 C 和 iOS,但遇到了问题。我正在从包含纬度和经度的 CoreData 创建一个数组。我想获取这个数组并按最近的位置对其进行排序。
这是我到目前为止所拥有的:
NSError *error = nil;
NSFetchRequest *getProjects = [[NSFetchRequest alloc] init];
NSEntityDescription *projectsEntity = [NSEntityDescription entityForName:@"TimeProjects" inManagedObjectContext:context];
[getProjects setEntity:projectsEntity];
projectArray = [[context executeFetchRequest:getProjects error:&error] mutableCopy];
for (NSObject *project in projectArray) {
// Get location of house
NSNumber *lat = [project valueForKey:@"houseLat"];
NSNumber *lng = [project valueForKey:@"HouseLng"];
CLLocationCoordinate2D coord;
coord.latitude = (CLLocationDegrees)[lat doubleValue];
coord.longitude = (CLLocationDegrees)[lng doubleValue];
houseLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
//NSLog(@"House location: %@", houseLocation);
CLLocationDistance meters = [houseLocation distanceFromLocation:currentLocation];
}
我也有这个排序代码,但我不确定如何将两者放在一起。
[projectArray sortUsingComparator:^NSComparisonResult(id o1, id o2) {
CLLocation *l1 = o1, *l2 = o2;
CLLocationDistance d1 = [l1 distanceFromLocation:currentLocation];
CLLocationDistance d2 = [l2 distanceFromLocation:currentLocation];
return d1 < d2 ? NSOrderedAscending : d1 > d2 ? NSOrderedDescending : NSOrderedSame;
}];
有人可以帮助我使这两件事一起工作吗?