ios - CoreData: Fetching entities with special condition -
in database, have entity called "address", there 140k rows of addresses. each address has attributes "lat" , "lng", indicating latitude , longitude of address.
provided have acquired user location location service, how traversing addresses , find address nearest user location?
i have code construct haversine distance if can latitude , longitude of address, problem don't know how in predicate.
my current code getting nearest addreses array:
// user location acquired location service cllocationcoordinate2d currentlocationcoordinate = location.coordinate; float dist = flt_max; int nearestaddressindex = -1; for(int = 0; < [addresses count]; ++i) { nsdictionary *address = addresses[i]; haversine *haverobject = [[haversine alloc] initwithlat1:currentlocationcoordinate.latitude lon1:currentlocationcoordinate.longitude lat2:[address[@"lat"] floatvalue] lon2:[address[@"lng"] floatvalue]]; if ([haverobject tometers] < dist ) { dist = [haverobject tometers]; nearestaddressindex = i; } }
is there way construct predicate? or must fetching addresses in array , traversing array?
i bit reluctant latter, worry might cause app terminate due memory pressure.
also similar question occur somewhere else in app:
in second case, need address falls within radius around user location. below code array:
cllocationcoordinate2d currentlocationcoordinate = location.coordinate; cgfloat threshold = 500.0f; nsmutablearray *nearbystation = [nsmutablearray array]; (nsdictionary *station in [datahelper sharedinstance].stations) { cgfloat lat = [station[@"lat"] floatvalue]; cgfloat lng = [station[@"lng"] floatvalue]; haversine *haverobject = [[haversine alloc] initwithlat1:currentlocationcoordinate.latitude lon1:currentlocationcoordinate.longitude lat2:lat lon2:lng]; if ([haverobject tometers] <= threshold) { [nearbystation addobject:station]; } }
i have above code datas stored in array. how same thing "address" stored in core data?
it's better if traverse 1 value of entity. try adapting this:
nsentitydescription *description = [nsentitydescription entityforname:@"address" inmanagedobjectcontext:[yourcontext managedobjectcontext]]; nsfetchrequest *request = [[nsfetchrequest alloc] init]; [request setentity:description]; nspredicate *predicate = [nspredicate predicatewithformat:@"examplelatitute < dist"]; [request setpredicate:predicate]; nserror *error = nil; nsarray *array = [[yourcontext managedobjectcontext] executefetchrequest:request error:&error];
Comments
Post a Comment