objective-c - NSSortDescriptor - 按位置排序

标签 objective-c ios cocoa-touch core-data core-location

我在 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”)排序的所有项目,而不是按用户当前位置排序。

看起来我的比较器 block 从未被调用过,因为其中的 NSLog 从未打印过。

我在这里错过了什么?

最佳答案

基于 Objective-C 的排序描述符不能用于获取请求。

摘自《核心数据编程指南》:

... To summarize, though, if you execute a fetch directly, you should typically not add Objective-C-based predicates or sort descriptors to the fetch request. Instead you should apply these to the results of the fetch.

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

相关文章:

iphone - map 的 didSelectAnnotationView 在 iphone sdk 中只调用一次

ios - 问题 : TMS-90809: Deprecated API Usage - Apple will stop accepting submissions of apps that use UIWebView APIs

iphone - 在 iPhone 中使用 UTF-8 进行编码和解码

iphone - UIButton TouchUpInside 不工作

ios - CAEmitter 平滑启动动画

ios - UITableView、Separator颜色在哪里设置?

iphone - 动画期间不能触摸( block 动画)

ios - objective-C 。非弧中的弧库

ios - 如何将 UIButton 连接到选项卡栏 Controller 中的特定选项卡?

objective-c - 我怎么知道是否有硬件键盘?