The problem is that I don’t know how can I make a NSPredicate that looks in two Entities. Any ideas?
Let’s assume I have 2 Entities:
Library:
1 lib_id
2 name
3 address
and:
Books
1 book_id
2 book_name
3 book_author
4 lib_id
There isn’t any Core Data Relation between them. I want to make a fetch request that will return an NSArray with all the libraries that contain at least one book.
I assume it’s something like this:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescriptor *entity = [NSEntityDescriptor entityForName:@"Books" inManagedObjectContext:context];
// some NSPredicate...
array = [context executeFetch ...];
It’s more complicated than you think, but it’s not impossible.
Your data model’s use of
lib_idon both entities, and your comment that you can’t add a Core Data relationship between the entities, suggests you’re falling into a classic trap: You’re treating Core Data like a relational database. Core Data’s API is not designed like a relational database. You can make it work that way, but you should be aware that you are going out of your way to make Core Data more difficult than necessary. If the solution below looks convoluted, it’s because you’re doing Core Data wrong.If you were using Core Data as it’s intended to be used– in this case with a relationship between the two entities– the lookup would be simple. You could just do a fetch for every
Librarywith no entries in itsbooksrelationship.With that said, you solve the immediate problem in two steps.
First, get every unique value of
lib_idthat’s used on instances ofBooks. The following will get you anNSArraycontaining strings that match the unique values:The last line above is there because
libIdsInBooksDictsactually contains an array of dictionaries, and each dictionary in turn has a key namedlib_idand a value that’s the actual ID. You just want the values.Next, look up every
Librarywhoselib_idis in the list you just got: