Aar*_*ger 4 cocoa-touch core-data objective-c core-location ios
我在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]);
Run Code Online (Sandbox Code Playgroud)
但是,我的NSFetchedResultsController只返回我指定的键("stop_lat")排序的所有项目,而不是按用户的当前位置排序.
看起来我的比较器块没有被调用,因为那里的NSLog从未打印过.
我在这里错过了什么?
基于Objective-C的排序描述符不能与获取请求一起使用.
来自"核心数据编程指南":
...但是,总而言之,如果直接执行提取,通常不应将基于Objective-C的谓词或排序描述符添加到提取请求中.相反,您应该将这些应用于获取的结果.
| 归档时间: |
|
| 查看次数: |
1598 次 |
| 最近记录: |