8

Is there a way to use a 'transient' field or something like that and in some way sort accordingly with a NSFetchedResultsController. I want to do the following:

I have location of places in a database. When a person opens the list, I want to show the nearest place on top, an then sort accordingly to distance. But clearly,this depends on the users location, so I cannot use a static field. I was hoping to use a transient field, as you can use for the section headers.

Is there anybody who can give a solution or workaround for this situation?

Luuk D. Jansen
  • 4,402
  • 8
  • 47
  • 90

1 Answers1

12

You cannot use a transient property in a fetch request for a SQlite base Core Data store.

See Fetching Managed Objects in the "Core Data Programming Guide":

You cannot fetch using a predicate based on transient properties (although you can use transient properties to filter in memory yourself). ... To summarize, though, if you execute a fetch directly, you should typically not add Objective-C-based predicates or sort descriptors to the fetch request. Instead you should apply these to the results of the fetch.

You can use a transient property for sectionNameKeyPath, but even then you need a first sort descriptor for the sections that is based on a persistent attribute.

So the only workaround is probably to fetch all objects and then sort the fetched array. But then of course you don't have the advantages of a fetched results controller anymore.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks Martin. I was thinking that maybe I could do something with the sections alright. Could off-course sort it manually or do a rough search near the users current coordinates, calculate and save the distances and fetch again, but is all is quite cumbersome. Thanks for the response, it is a putty, but understandable, that it is not possible in this scenario. – Luuk D. Jansen Nov 10 '12 at 22:55
  • I went for the option to select the locations within the region (by latitude/longitude), populate a distance field, and then sort accordingly. A bit ,ire overhead, but it works. – Luuk D. Jansen Nov 20 '12 at 08:31
  • 1
    Which is the same as I did after asking, see: http://stackoverflow.com/questions/3934418/what-is-the-fastest-way-to-sort-a-lot-of-locations-on-distance My optimization of computing and storing, but not saving the context, might help speed things up. – Bjinse Mar 26 '14 at 10:39