代码之家  ›  专栏  ›  技术社区  ›  jame

获取核心数据关系中的对象数

  •  4
  • jame  · 技术社区  · 16 年前

    我有一个食谱的桌面视图。用户可以添加和删除配方。 单击一个配方时,会推送另一个tableview,并显示配料。同样,用户可以添加和删除成分。

    食谱和配料之间有着千丝万缕的联系。

    我想在recipe tableview行中显示配料的数量。我知道如何在interface builder中设置所有行,但我不知道如何获得单个配方的配料数。

    这可能吗?

    3 回复  |  直到 9 年前
        1
  •  12
  •   Ken Aspeslagh    16 年前

    使用countForFetchRequest而不是executeFetchRequest,并且(对于SQL支持的存储),它将进行计数而不是选择。

        2
  •  10
  •   Helephant    16 年前

    如果您使用的是核心数据,您可以通过调用count方法询问成分列表,其中包含多少成分:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        int count = [recipe.ingredients count];
        return count;
    }
    

    通过查看 NSSet class in the documentation .

    通过查看核心数据创建的生成类,我找到了要查看的类:

    @class ParentObject;
    @interface ParentObject :  NSManagedObject  
    {
    }
    @property (nonatomic, retain) NSString * name;
    @property (nonatomic, retain) NSSet* childObjects;
    @end
    
        3
  •  1
  •   Alex Reynolds    16 年前

    只需使用一个允许所有匹配项的谓词获取所有成分。这 NSFetchRequest 将返回一个 NSArray ,执行时。做一个 [myArray count] 获取配料的数量。