简体   繁体   中英

Fetching contacts based on tag

I'm trying to modify a simple Core Data fetch request for contacts to only look for contacts with a relationship with a certain tag. Contact and Tag are both entities with a many-to-many relationship.

I understand with Core Data I can do this by first fetching the Tag object, and then calling tag.contact , but I don't want to do it this way as the rest of the code is dependent on the fact that the fetchResultsController returns Contact objects, not Tag objects.

If I were to do relational databasing, I could do a simple cross-table query and find all contacts with a certain tag. Is there a simple way I can replicate this via Core Data?

-(NSFetchedResultsController *) fetchedResultsController {

    //if fetch controller already exists
    if(_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    //create a new fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact"
                                              inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

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

    //instantiate the fetch controller with the fetch request and sort by last name into sections
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];

    //declare delegate of fetch controller as self
    _fetchedResultsController.delegate = self;

    NSLog(@"fetchResultsController Created");
    return _fetchedResultsController;
}

Use NSPredicate .

Lets say you have related Contacts with Tag by name tags and tag entity has property name.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY tags.name = [cd] %@", @"sales"];
[fetchRequest setPredicate:predicate];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM