我在 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 永远不会打印。

我在这里缺少什么?

最佳答案

基于 Objective-C 的排序描述符不能与 fetch 请求一起使用。

来自“核心数据编程指南”:

关于objective-c - NSSortDescriptor - 按位置排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12027769/

10-11 07:53
查看更多