如何编写NSPredicate for Core Data to-many关系

时间:2011-01-30 20:15:03

标签: core-data nsfetchedresultscontroller nspredicate

我在导航层次结构中有2个UITableViews级别。在第一页上是UITableView,它使用Equipment显示NSFetchedResultsController的所有实例,效果很好。在第二页上,我想要取回Note特定内容的所有Equipment个实体,以便我可以在tableView中显示它们。

如何撰写NSPredicate仅返回相关注释?

Table Relationship

- (NSFetchedResultsController *)fetchedResultsController {

    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    //Init Fetch Request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    //Entity the NSFetchedResultsController will be managing
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Note" 
                                              inManagedObjectContext:self.myContext];
    [fetchRequest setEntity:entity];

    //Sort Descriptors
    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"noteTime" 
                                                                    ascending:YES];//Primary Sort
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"noteText" 
                                                                    ascending:YES];//Secondary Sort
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, 
                                                                sortDescriptor2, 
                                                                nil];

    //Set Sort Descriptors
    [fetchRequest setSortDescriptors:sortDescriptors];

    // limit Fetch to notes that belong to myEquipment
    //self
   // NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"item.name like '%@'", self.item.name]];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:PREDICATE GOES HERE];
    [fetchRequest setPredicate:predicate];



    [fetchRequest setFetchBatchSize:10];

    NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest    
                                                                          managedObjectContext:self.myContext 
                                                                            sectionNameKeyPath:nil 
                                                                                     cacheName:@"Equipment"];
    //Set the Delegate Property
    frc.delegate = self;
    _fetchedResultsController = frc; 

    //Release Local Memory
    [sortDescriptor1 release];
    [sortDescriptor2 release];
    [sortDescriptors release];
    [fetchRequest release];

    return _fetchedResultsController;
} 

1 个答案:

答案 0 :(得分:4)

看看core data documentationthe predicate programming guide你应该看到你必须做的事情

Equipment *equipment = // your equipment was passed from the previous tableview controller
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"equipment == %@", equipment];