【发布时间】:2014-04-24 13:09:19
【问题描述】:
我想从我的特定位置获取半径 5 公里内的所有对象。目前我有以下内容:
_searchDistance = 2.50;
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
float minLat = appDelegate.latitude - (_searchDistance / 69);
float maxLat = appDelegate.latitude + (_searchDistance / 69);
float minLon = appDelegate.longitude - _searchDistance / fabs(cos(appDelegate.longitude / 180.0 * M_PI)*69);
float maxLon = appDelegate.longitude + _searchDistance / fabs(cos(appDelegate.longitude / 180.0 * M_PI)*69);
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Relation" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"rel_latitude <= %f AND rel_latitude >= %f AND rel_longitude <= %f AND rel_longitude >= %f", maxLat, minLat, maxLon, minLon];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"rel_name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sort,nil]];
NSArray *matches = [context executeFetchRequest:fetchRequest error:nil];
这段代码基于以下stackoverflow question
但这会在当前位置周围创建一个正方形。这会导致返回错误的值。那么有人可以帮我解决这个问题吗?
【问题讨论】:
-
错误值是什么意思? - 当然,您的谓词会得到一个“正方形”。如果实体中仅存储纬度/经度,则无法获取给定距离内的对象,因为谓词和排序描述符都只能使用 persistent 属性。 - 正如我试图在上一个问题的答案中解释的那样,您必须将距离存储为持久属性,或者在内存中过滤获取的对象(您可以使用任何基于 Objective-C过滤器)。
-
@MartinR 我确实理解你的回答。但我的问题是现在我们可以把正方形变成圆形吗?他们不存在一些数学公式吗?
-
xmin <= x <= xmax AND ymin <= y <= ymax是正方形,(x-x0)^2 + (y-y0)^2 <= r^2是圆形。在核心数据获取请求中允许第一个,但第二个不允许。 (这是核心数据限制,而不是 SQL 限制)。除了首先获取封闭正方形的对象然后再次在内存中过滤之外,我没有看到其他解决方案。
标签: objective-c core-data nspredicate latitude-longitude nsfetchrequest