Core Data Parent

I have an abstract object A, I also have two objects whose parents are Entity A. Each child has a different relationship with other objects.

I am trying to retrieve all child entities of Entity A for which the boolean value of isPublic is YES.

I had problems retrieving the Entities subclass in the past with respect to the selection, and I'm sure I just am not doing it right.

Thus, we could say, for example: • Object A is “Document”, • Object B is “Poem”, • Entity C is “Article”

All documents are a subclass of poems and articles, and the document has a property called isBookmarked, suer can bookmark a poem or article, and I need a way to get all the documents that are bookmarked. Entities B and C must be independent due to other relationships that they own.

I want to use NSFetchedResultsController for optimal Core Data and UITableView performance, and I'm struggling to put together a mixture of poems and articles.

What selection request will give me a mixture of poems and articles?

enter image description here

+4
source share
2 answers

How about something simple (which assumes isBookmarked is logical):

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Document" inManagedObjectContext:context]; // This may not be the most elegant way of using a boolean in a predicate, but… NSNumber *numIsBookmarked = [NSNumber numberWithBool:YES]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isBookmarked == %@", numIsBookmarked]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity: entityDescription]; [request setPredicate: predicate]; [request setResultType: NSManagedObjectResultType]; NSError *error = nil; NSArray *results = [contextMain executeFetchRequest:request error:&error]; if (error) { // deal with the error } [request release]; 

Then you will check which subclass was extracted:

 for (NSManagedObject *obj in results) { if ([obj isKindOfClass:[Poem class]]) { // do whatever } else if ([obj isKindOfClass:[Article class]]) { // do whatever } } 

(Alternatively, if some of the subclass MOs implement the same method, it may be more efficient to run the respondsToSelector: test.)

This does not work?

+4
source

Wienke answer should work if you just added

 [request setIncludesSubentities:YES]; 

otherwise, you will only get the results of object A, which should not be specified, as you said, is abstract.

+5
source

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


All Articles