Вопрос

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.

Это было полезно?

Решение 2

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top