我仍在學習目標C和iOS,並且遇到問題。我從CoreData創建一個包含緯度和經度的數組。我想把這個數組按照最近的位置排序。如何按距離排序數組iOS
這是我到目前爲止有:
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;
}];
有人能幫我把這兩樣東西一起工作嗎?
你在循環之前放了'sortUsingComparator'節嗎? – Wain
什麼不起作用? –