NSFetchedResultsController and Entity Inheritance

I have a parent in my Event model. And two children: Birthday, Anniversary. I use the object inheritance function built into Core data, so the parent of the birth and anniversary is an event.

So, I am making a selection using the following:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Set the batch size to a suitable number. [fetchRequest setFetchBatchSize:20]; // Edit the sort key as appropriate. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"start_date" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil]; etc... 

Now I want to sort fetchedObjects by event type, birthday or anniversary.

How can I do it? I tried:

 for (Birthday *birthday in _fetchedResultsController.fetchedObjects){ [birthdayObjects addObject:birthday]; } for (Anniversary *anniversary in _fetchedResultsController.fetchedObjects){ [anniversaryObjects addObject:anniversary]; } 

But it just adds all the objects in fetchedObjects to each array.

Any ideas, or am I not mistaken about this?

UPDATE :

It turned out using this:

 for (Event *event in _fetchedResultsController.fetchedObjects){ if ([event isKindOfClass:[Birthday class]]){ [birthdayObjects addObject:event]; }else{ [anniversary addObject:event]; } } 

But if there is a better way, I am open to this! Thank you

+4
source share
1 answer

Has a read-only property in Event called eventType or the like that returns a string. The Event class returns a single row, and your child events return a Birthday, Anniversary anniversary, and everything else for future types of events.

In your resulting result controller, if you use it, you can set eventType as the key path to the section name, and this will divide the types into sections for you - transient properties like this are suitable for this purpose, but you cannot use them as part of the selection request.

In the above situation, use the event type as a predicate or sort descriptor to handle an array of all the events returned from the select query.

If you don't like the string, you can use an enumeration. If you want to use the event type in a query, make it an attribute of the Event class and set it accordingly to awakeFromInsert.

0
source

Source: https://habr.com/ru/post/1400409/


All Articles