Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData: Fetch and sort results in the order they were created, without using a timestamp

This is a pretty straightforward problem.

I have a CoreData database that gets initialized with a local file. The CoreData schema that looks like this:

Category -->> Objections -->> Responses -->> Evidence

("-->>" means, has many)

I am using an NSFetchedResultsController to retrieve objects from core data. Pretty standard.

NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([OHObjection class])inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"[suitable key]" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];

[fetchRequest setSortDescriptors:sortDescriptors];

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"category.objectionCategoryText" cacheName:nil];

Every "To Many" relationship is ordered.

Question: Is it possible to fetch the data in the order that it was created without using a timestamp or explicitly setting my own id?

Note: I have nothing against using timestamps or creating my own ID's, I just want to know if it is possible.

like image 715
Emin Israfil iOS Avatar asked Feb 24 '14 18:02

Emin Israfil iOS


2 Answers

From the Core Data Programming Guide:

How do I fetch objects in the same order I created them?

Objects in a persistent store are unordered. Typically you should impose order at the controller or view layer, based on an attribute such as creation date. If there is order inherent in your data, you need to explicitly model that.

So yes, you must use a timestamp or explicitly set your own id.

like image 159
pkamb Avatar answered Nov 06 '22 15:11

pkamb


The creation order is not recorded in the data store, so no.

If you have an ordered relationship and you make sure that you add objects to this relationship in the same order as you create them, then that order will be preserved. You won't get that by directly fetching the objects though, you'll get it by traversing the relationship (i.e. by looking them up on the object that has the ordered relationship).

For any other situation, the only ordering is the one you assign-- timestamps, unique IDs, etc.

If you use timestamps, make sure to use enough precision to handle multiple objects created in a loop (e.g. 1 second precision is almost certainly not good enough). If you use an ID that increments, make sure to assign values on a single queue, to avoid duplicates from multithreading.

like image 6
Tom Harrington Avatar answered Nov 06 '22 16:11

Tom Harrington