我在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从不打印。
这里我漏掉了什么?
发布于 2012-08-19 23:51:38
基于Objective-C的排序描述符不能与fetch请求一起使用。
摘自"Core Data Programming Guide":
...不过,总而言之,如果直接执行fetch,通常不应该向fetch请求添加基于Objective-C的谓词或排序描述符。相反,您应该将这些应用于fetch.
的结果
发布于 2012-11-14 22:14:38
另一种方法是在你的“Stop”managedObject上有一个名为meanSquared的属性(可能是一个NSDecimalNumber)。
当您的设备纬度/纬度移动到足以更改“最近停止”数据时,您可以使用meanSquared距离更新所有“停止”对象(即(您的纬度-停止高度)^2+(您的经度-停止长度)^2),然后只需在sortDescriptor中使用“meanSquared”即可。
根据您更新用户位置的次数、停靠点之间的距离和停靠点的数量,这可能是最佳解决方案。
发布于 2012-08-20 03:47:29
无论如何,您不能按经度/经度排序,您需要计算每个点的距离并按此进行排序。或者获取用户附近的一系列经度/经度值,获取该子集,计算它们的距离并显示。取值范围类似于用户的纬度+/- 0.1度,等等。
https://stackoverflow.com/questions/12027769
复制相似问题