问题
I have a parent entity in my model Event. And two child entities: Birthday, Anniversary. I'm using the entity inheritance feature built into Core data such that birthday and anniversary's parent object is Event.
So I do a fetch 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 the fetchedObjects by event type, birthday or anniversary.
How do I do that? I tried:
for (Birthday *birthday in _fetchedResultsController.fetchedObjects){
[birthdayObjects addObject:birthday];
}
for (Anniversary *anniversary in _fetchedResultsController.fetchedObjects){
[anniversaryObjects addObject:anniversary];
}
But this just adds all objects in the fetchedObjects to each array.
Any ideas or am I going about this the wrong way?
UPDATE:
Figured it 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 it! Thanks.
回答1:
Have a read-only property on Event, called eventType or similar, which returns a string. Your Event class returns one string, and your child events return Birthday, Anniversary, whatever else for future event types.
In your fetched results controller, if you use one, you can set eventType as your section name key path and this will divide the types into sections for you - transient properties like this are fine for this purpose, but you can't use them as part of the fetch request.
In the situation above, use the event type as a predicate or sort descriptor to process the array of all events that comes back from the fetch request.
If you don't like a string, you could use an enum. If you want to use the event type in a fetch request, make it an attribute of the Event class and set it appropriately on awakeFromInsert.
来源:https://stackoverflow.com/questions/9620954/nsfetchedresultscontroller-and-entity-inheritance