title: How to sort an array by distance with iOS
body: <p>I'm still learning objective C and iOS and I'm running into a problem. I am creating an array from CoreData that contains latitudes and longitudes. I want to take this array and sort it by the closest location.</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>NSError *error = nil;
  NSFetchRequest *getProjects = [[NSFetchRequest alloc] init];
  NSEntityDescription *projectsEntity = [NSEntityDescription entityForName:@"TimeProjects" inManagedObjectContext:context];
  
  [getProjects setEntity:projectsEntity];
  projectArray = [[context executeFetchRequest:getProjects error:&amp;error] mutableCopy];
  
  for (NSObject *project in projectArray) {
      // Get location of house
      NSNumber *lat = [project valueForKey:@"houseLat"];
      NSNumber *lng = [project valueForKey:@"HouseLng"];
  
  
      CLLocationCoordinate2D coord;
      coord.latitude = (CLLocationDegrees)[lat doubleValue];
      coord.longitude = (CLLocationDegrees)[lng doubleValue];
  
      houseLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
      //NSLog(@"House location: %@", houseLocation);
  
      CLLocationDistance meters = [houseLocation distanceFromLocation:currentLocation];
  
  }
  </code></pre>
  
  <p>I also have this sorting code but I'm not sure how to put the two together.</p>
  
  <pre><code>[projectArray sortUsingComparator:^NSComparisonResult(id o1, id o2) {
      CLLocation *l1 = o1, *l2 = o2;
  
      CLLocationDistance d1 = [l1 distanceFromLocation:currentLocation];
      CLLocationDistance d2 = [l2 distanceFromLocation:currentLocation];
      return d1 &lt; d2 ? NSOrderedAscending : d1 &gt; d2 ? NSOrderedDescending : NSOrderedSame;
  }];
  </code></pre>
  
  <p>Can some one help me out with making these two things work together?</p>