Fogmeister
Fogmeister

Reputation: 77631

NSSortDescriptor with Comparator using actual object not a key value

I have an entity in CoreData MyObject which has properties latitude and longitude.

I'd like to perform a fetch with an NSFetchedResultsController that sorts the fetch by the distance the MyObject is from the user's current location.

However, I don't know what to put in the Key part of the sort descriptor.

I don't want to compare a particular key of the object. I want to compare the objects themselves.

I'm not sure how it's possible for me to do this without repopulating the distance field of the records.

I'm trying to use this code...

[[NSSortDescriptor alloc] initWithKey:@"." ascending:YES comparator:^NSComparisonResult(MyObject *object1, MyObject *opject2) {
    // stuff here
}];

But it crashes the app due to memory pressure (lol).

Obviously using @"." is not correct but is there a way of doing this?

Or is there a better way of doing this using a different approach?

Upvotes: 1

Views: 756

Answers (1)

Pradeep K
Pradeep K

Reputation: 3661

If you don't want to sort the objects by their keys but instead sort the objects themselves then you should not use Sort descriptors. Just get the array of the results and then sort that array. Of course your custom object MyObject should implement isEqual in order to do this.

Another alternative is to add a new key called distance to the MyObject and then use it as the key for the sort descriptor.

  1. Create NSFetchRequest for the MyObject entities from the CoreData
  2. executeFetchRequest to fetch all the locations in the database.
  3. Iterate thru the MyObject array and populate the distance property by calculating the distance between the currentLocation and the MyObject's location (lat,long)
  4. Set the sortDescriptor of the fetch request created in 1 to distance
  5. Create a FRC using this fetch request and call performFetch
  6. Use the fetchedObjects of the FRC which will be in sorted order according to the distance.

Hope this works for you.

Upvotes: 2

Related Questions