I’m trying to display some Spots in a UITableView with NSFetchedResultsController associated to the Database.
The problem is that I need to filter the results by a distance (radio) from a specific Location. I read that it is not possible to a NSPredicate that calculate distance, so I’m getting all the Spots in an area around the Location with a simple comparation with the coordinates. That gives me a Square around the Location. Then, I want to iterate the results of the fetchedObjects and remove the ones that are not in the Zone.
- (NSFetchedResultsController *)newFetchedResultsControllerWithSearch:(NSString *)searchString{
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:sectionName
cacheName:@"Stores"];
aFetchedResultsController.delegate = self;
NSError *error = nil;
if (![aFetchedResultsController performFetch:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
// ITERATE FETCHED OBJECTS TO FILTER BY RADIO
int n = [aFetchedResultsController.fetchedObjects count];
NSLog(@"Square result count: %i",n);
self.footerLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%i Spots", @"%i Spots"),n];
return aFetchedResultsController;
How can I remove object from the aFetchedResultsController.fetchedObjects before returning it?? Will it alterate the methods used in UITableView like [fetchedResultsController objectAtIndexPath:indexPath] ?
Thanks
You cannot modify the result set of a fetched results controller (FRC). You can filter the results, but that does not help if the FRC is used as data source for a table view.
Possible solutions:
Pre-calculate the distances to the current locations and store the distances as a persistent attribute in the database. Then you can use a filter on the distance directly in the fetch request of the FRC. The big disadvantage of course is that you have to re-calculate the distances when the current location changes.
Don’t use a fetched results controller. Perform a fetch request and filter the results of the fetch request according to the radius into an array, and use this array as data source for the table view. The big disadvantage here is that you lose the automatic update features of the FRC. You would have to reload the table view each time the radius or other search parameters are changed.
I know that both solutions are not satisfying, but I don’t think there is a method to combine a fetched results controller with a function based filter.