Sorting results from CoreData Fetch

In this case, you want to compare a CLLocation from the user to the lat & long you have on your CoreData:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:self.managedObjectContext]

[fetchRequest setEntity:entity];

NSArray *arrayOfEntities = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

arrayOfEntities = [arrayOfEntities sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(id obj1, id obj2)
{
    CLLocation *obj1EntityLocation = [[CLLocation alloc] initWithLatitude:[(NSNumber*)[obj1 valueForKey:ENTITY_LAT_KEY] doubleValue]longitude:[(NSNumber*)[obj1 valueForKey:ENTITY_LONG_KEY] doubleValue]];

    CLLocation *obj2EntityLocation = [[CLLocation alloc] initWithLatitude:[(NSNumber*)[obj2 valueForKey:ENTITY_LAT_KEY] doubleValue]longitude:[(NSNumber*)[obj2 valueForKey:ENTITY_LONG_KEY] doubleValue]];

    CLLocationDistance dist1 = [obj1EntityLocation distanceFromLocation:userLocation];
    CLLocationDistance dist2 = [obj2EntityLocation distanceFromLocation:userLocation];

    return [[NSNumber numberWithDouble:dist1] compare:[NSNumber numberWithDouble:dist2]];
}];

return arrayOfEntities;
}

The point is to be able to sort an array that comes from CoreData in a nonlinear way, by using Blocks.

Advertisements
Tagged , , , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: