Alexander
Alexander

Reputation: 7238

CoreData Fetch Predicate for unrelated entities

I am having trouble to do a CoreData fetch request for unrelated entities. Lets assume I have an object model with 3 entities: Message, User and Advisor.

I want this 3 objects to be unrelated to each other. So a Message does have an attribute senderEmail and receiverEmail whilst User and Advisor do have the attribute email.
But again, there is no further relationship between those objects.
I now want for example to fetch the latest (newst) Message by an advisor or by a user. But how should I do this fetch predicate since the objects are not connected?

Is this even possible within one Fetch Request or do I need to fetch each objects separately into an array and then make further operations to get what I want?

Upvotes: 0

Views: 282

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

Alexander,

if those entities are not related each other you need to excecute different fetch requests to grab your data.

So, for example, you could grab the latest Message setting up a request like the following:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"senderEmail == %@", grabbedEmail];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"insertionDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

NSFetchRequest *messageFetch = [[NSFetchRequest alloc] init];
[messageFetch setEntity:[NSEntityDescription entityForName:@"Message" inManagedObjectContext:yourContext]];
[messageFetch setPredicate:predicate];
[messageFetch setSortDescriptors:sortDescriptors];
[messageFetch setFetchLimit:1];

To retrieve the grabbedEmail (if you don't have it) you need to set up a request with a specific predicate. The same could be applied for the receiver email. For example.

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"userId == %@", @"someUserId"];

NSFetchRequest* userFetch = [[NSFetchRequest alloc] init];
[userFetch setEntity:[NSEntityDescription entityForName:@"User" inManagedObjectContext:yourContext]];
[userFetch setPredicate:predicate];
[userFetch setFetchLimit:1];

NSArray* userResults = [userFetch executeFetchRequest:&error];

User* retrievedUser = (User*)[userResults objectAtIndex:0];
NSString* grabbedEmail = [retrievedUser email];

To sort by date you could simply add to Message enitity an attribute called insertionDate (of type NSDate) that allows you to order by date.

When you execute the request

NSArray* results = [messageFetch executeFetchRequest:&error];

the array results will contain the (only) Message element you are looking for.

Why do you need to maintain separate those entities?

Hope that helps.

Upvotes: 1

Related Questions