首页 文章

使用托管对象中的集合作为获取结果控制器的数据

提问于
浏览
1

我想创建一个导航界面,用户可以点击一个单元格并拥有一个与前一个相同的新导航控制器 . 我的托管对象具有以下结构:

name (string)
orderId (int)
orderBy (string, a key path indicating what to order the table with)
dateCreated (date)
items (a relationship pointing to the items for the next table)

在点击具有非零项目的项目时,下一个控制器获得对被点击项目的引用,并使用其“items”,“orderBy”和“orderId”构建一个获取的结果控制器(其项目为数据)和排序描述符(使用orderBy和OrderId) .

如何告诉获取的结果控制器使用项目返回的 NSSet 作为其数据?我可以使用谓词将结果限制为仅一个对象的项目吗?谢谢

1 回答

  • 1

    您的物品需要具有相反的多对一关系 . 让我们称这种关系为“父母” .

    在tableView委托的didSelectRowAtIndexPath:中,启动一个新的视图控制器,并在所述indexPath处传递“父”对象 . 您将需要创建一个访问器来在下一个视图控制器中保存所述对象 .

    正如您猜测的那样,您可以创建一个谓词,以便fetchedResultsController只返回所说的“items” . 使您获取的结果仅搜索“item”实体 .

    NSPredicate *resultsPredicate = [NSPredicate predicateWithFormat:@"parent == %@", parentObject];
    [fetchRequest setPredicate:resultsPredicate];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
        initWithKey:[parentObject valueForKey:@"orderBy"] ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    

    基本上,您正在搜索与所选对象具有父关系的所有“项目” .

    让我知道我是否正确描述(对不起,如果我没有,但我自己这样做,并可以指向Apple的例子) .

    编辑:Apple示例代码

    http://developer.apple.com/library/ios/#samplecode/CoreDataBooks/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008405

    http://developer.apple.com/library/ios/#samplecode/iPhoneCoreDataRecipes/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008913

相关问题