我在 Core Data 中有一个地理位置列表(实体名称是“Stops”)。
我想按当前位置对它们进行排序,以便向用户显示附近的位置。我正在使用 NSFetchedResultsController 以便结果可以轻松地显示在 UITableView 中。
我正在使用以下代码来尝试这种排序:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"stop_lat" ascending:YES comparator:^NSComparisonResult(Stops *obj1, Stops *obj2) {
CLLocation *currentLocation = locationManager.location;
CLLocation *obj1Location = [[CLLocation alloc]initWithLatitude:[obj1.stop_lat doubleValue] longitude:[obj1.stop_lon doubleValue]];
CLLocation *obj2Location = [[CLLocation alloc]initWithLatitude:[obj2.stop_lat doubleValue] longitude:[obj2.stop_lon doubleValue]];
CLLocationDistance obj1Distance = [obj1Location distanceFromLocation:currentLocation];
CLLocationDistance obj2Distance = [obj2Location distanceFromLocation:currentLocation];
NSLog(@"Comparing %@ to %@.\n Obj1 Distance: %f\n Obj2 Distance: %f",obj1.stop_name, obj2.stop_name, obj1Distance, obj2Distance);
if (obj1Distance > obj2Distance) {
return (NSComparisonResult)NSOrderedDescending;
}
if (obj1Distance < obj2Distance) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setEntity:[NSEntityDescription entityForName:[Stops entityName] inManagedObjectContext:context]];
frcNearby = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:nil];
NSError *error;
BOOL success = [frcNearby performFetch:&error];
if (error) NSLog(@"ERROR: %@ %@", error, [error userInfo]);
但是,我的 NSFetchedResultsController 只是返回按我指定的键(“stop_lat”)排序的所有项目,而不是按用户当前位置排序。
看起来我的比较器块从未被调用过,因为那里的 NSLog 从不打印。
我在这里想念什么?