Alex Saidani
Alex Saidani

Reputation: 1307

Fetch Data According To Specific Entity

I am using magical record to fetch data from core data, using the code:

- (NSFetchedResultsController *)fetchedResultsController {
    if (!_fetchedResultsController ) {
        _fetchedResultsController = [TagItem MR_fetchAllGroupedBy:nil withPredicate:nil  sortedBy:@"name" ascending:YES delegate:self];
    }

    return _fetchedResultsController;
}

The problem is, it is populating a table view controller that is pushed to by another table view controller, so basically a user selects an option which takes the person to a list of data, but the data within the option is specific to that option. So what I want to do is fetch only the data that is assigned to that option, rather than simply displaying all the data available. My method above only allows me to obtain all the data, rather than selecting specific data according to the option. The data within the option is given the objectId of the option itself as an entity and thus provides a relationship between the two.

So my question is, how do I go about fetching data according to a specific entity, using magical record?

UPDATE

I have tried setting the predicate to a specific value just to test if it works, thinking it would work the same as just working with core data alone, but I just get an error.

- (NSFetchedResultsController *)fetchedResultsController {
    if (!_fetchedResultsController ) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = test"];
        _fetchedResultsController = [TagItem MR_fetchAllGroupedBy:nil withPredicate:predicate  sortedBy:@"name" ascending:YES delegate:self];
    }



return _fetchedResultsController;

}

The error is as below, even though I know for certain there is a data item with the name test stored, nonetheless it doesn't seem to work.

'NSInvalidArgumentException', reason: 'Unable to generate SQL for predicate (name == test) (problem on RHS)'

Upvotes: 0

Views: 862

Answers (1)

Martin R
Martin R

Reputation: 539735

That's what the withPredicate parameter is for:

NSPredicate *predicate = ... // predicate that filters the items to display
_fetchedResultsController = [TagItem MR_fetchAllGroupedBy:nil withPredicate:predicate ...];

For example, if TagItem has a to-one relationship person to Person, then

Person *person = ...; // person selected in the first view controller
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person = %@", person];
_fetchedResultsController = [TagItem MR_fetchAllGroupedBy:nil withPredicate:predicate ...];

would fetch all items related to that person.

Upvotes: 4

Related Questions