核心数据检索关系数据

时间:2013-11-09 18:59:31

标签: core-data

enter image description here

我在检索通过Menu实体创建的项目时遇到了问题。这是我用来将项添加到特定Menu对象的代码

-(void)additem:(NSString *)entity :(NSDictionary *)aDictionary :(NSString *)menu
{
   NSLog(@"additem");
   NSError *error = nil;

   Menu *menuItem = nil;

   NSFetchRequest * request = [[NSFetchRequest alloc] init];
   [request setEntity:[NSEntityDescription entityForName:@"Menu"       inManagedObjectContext:managedObjectContext]];

[request setPredicate:[NSPredicate predicateWithFormat:@"mname=%@ and msection =%@",@"Parents",@"Keydates"]];

menuItem = [[managedObjectContext executeFetchRequest:request error:&error] lastObject];

if (error) {
    //Handle any errors
}
if (!menuItem) {
    //Nothing there to update
    NSLog(@"This class doesn't exist");
}

Items *anitem = (Items *)[NSEntityDescription insertNewObjectForEntityForName:@"Items" inManagedObjectContext:managedObjectContext];;
anitem.type = [aDictionary objectForKey:@"type"];
anitem.title = [aDictionary objectForKey:@"title"];
anitem.image = [aDictionary objectForKey:@"image"];
anitem.subtitle = [aDictionary objectForKey:@"subtitle"];

[menuItem addItemsObject:anitem];

[managedObjectContext save:&error];

}

我想使用谓词来检索在特定Menu对象上创建的所有项目。这是我试图用它来检索它的代码。

- (void) readItems: (NSString *)section {


    NSLog(@"readItems");
    NSError *error = nil;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Menu"
                                          inManagedObjectContext:managedObjectContext];
    fetchRequest.resultType = NSDictionaryResultType;

    [fetchRequest setEntity:entity];

    [fetchRequest setReturnsObjectsAsFaults:NO];

    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"mname=%@ and msection = %@",@"Parents",@"Keydates"]];


    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    for (Items *item in fetchedObjects) {
        NSLog(@">>>>>>%@",item);
    }
}

任何人都可以指出我正确的方向。我知道我通过了部分并且不使用它。我已将实际值放在。

1 个答案:

答案 0 :(得分:0)

您的readItems:方法将获取的实体指定为Menu但是当您执行fetch时,您期望Item(因为您开始迭代fetchedObjects并将它们作为Item进行转换)。

相反,您想要做的是将您的实体与Item相关联,并将谓词更改为

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"items.mname=%@ and items.msection = %@",@"Parents",@"Keydates"]];

此外,您应该考虑重命名您的人际关系。关系字段确切地指定了您按照箭头时期望看到的内容。因此,当我查看Items并按照箭头指向Menu时,我希望这个关系的名称是菜单,你称之为menuItems。您已正确完成了从菜单到项目的关系。

这样我们最终会得到一个更易读的谓词:

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"menu.mname=%@ and menu.msection = %@",@"Parents",@"Keydates"]];

快乐编码