Search code examples
objective-cioscore-datanspredicatensfetchrequest

Fetching data using Core Data


I have searched quite a lot on the internet but can't find what I'm looking for.

I have this model where it could be a lot of users. So I have an entity called User. The user has an NSSet of records. And I want to fetch records from given user. I'm trying to do it like this but it still returns records from all users.

NSManagedObjectContext *context = _backgroundContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Record"
                                                  inManagedObjectContext:context];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@)",date];
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"User = %@",currentUser];

NSPredicate *predicates = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:predicate,predicate1, nil]];
[fetchRequest setPredicate:predicates];

[fetchRequest setPredicate:predicate];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

I know it shouldn't be hard, but I can't find what it is, and I'm hoping some of you could help. Thanks in advance!

EDIT:

As I said I have an entity User which has:

NSString name,
int age,
NSSet records, ...

Record has its own properties such as:

NSDate date,
NSString name,
NSString event, 
...

I want to form a fetch request to get records just from specific user. And I don't know how to do it, because I'm getting all of the records from every user.

records has a To-Many relationship. I can get records like currentUser.records, but i can't get user using record.User.


Solution

  • The error is here:

    [fetchRequest setPredicate:predicates];
    [fetchRequest setPredicate:predicate];
    

    After setting the compound predicate, you overwrite it with the predicate for date alone. You probably want to delete the second line.

    EDIT: The fetch request requires that you have defined a inverse relationship user from Record to User and use the exact name of this relationship in the predicate.

    An alternative solution is to use the "forward" relationship from User to Record and filter the result:

    NSSet *records = [currentUser.records filteredSetUsingPredicate:predicates];
    

    or, if you prefer an array

    NSArray *records = [[currentUser.records allObjects] filteredArrayUsingPredicate:predicates];