Ios Coredata中的子级计数

Ios Coredata中的子级计数,ios,objective-c,core-data,nsfetchrequest,Ios,Objective C,Core Data,Nsfetchrequest,我需要根据逻辑找出孩子的数量 我有表A,它有两个关系B和C。现在我需要找到B和C的计数。 计数=B的数量*C的数量 数据: 总数=6 我试过以下方法 NSEntityDescription *entity = [NSEntityDescription entityForName:@"A" inManagedObjectContext:context]; NSArray *allObjects = [context executeFetchRequest:fetchRequest error:&a

我需要根据逻辑找出孩子的数量

我有表A,它有两个关系B和C。现在我需要找到B和C的计数。 计数=B的数量*C的数量

数据:

总数=6

我试过以下方法

NSEntityDescription *entity = [NSEntityDescription entityForName:@"A" inManagedObjectContext:context];
NSArray *allObjects = [context executeFetchRequest:fetchRequest error:&fetchError];
NSInteger totalCount= 0;

for(A *a in allObjects)
{
    NSInteger countOfB = [a.B count];
    NSInteger countOfc = [a.C count];
    totalCount = totalCount + (countOfB * countOfc);
}

这工作很好。但是当我有10000张唱片的时候,这需要更多的时间。如果有其他方法,请建议我。

不要按要求进行乘法运算。每当
A
实例与
B
C
的关系发生更改时,计算产品并将其存储在
A
上的新属性中。现在,要获取总计数,您可以只使用一次获取(返回字典类型),然后使用
@sum
(使用带有集合运算符的数组),并且不需要将任何对象实际加载到内存中


考虑使用KVO监视关系更改并触发产品更新。

尝试另一种方法,使用
NSPredicate
,获取
B
C
对象,这些对象具有
a
对象(在其关系中)和使用
@count
。请您提供一些使用@count的示例代码。我尝试过使用NSExpression,但这会给出B和c的计数。如果我考虑上面的例子:3(B的计数)* 4(C的计数)=12。这是给错了值。
NSEntityDescription *entity = [NSEntityDescription entityForName:@"A" inManagedObjectContext:context];
NSArray *allObjects = [context executeFetchRequest:fetchRequest error:&fetchError];
NSInteger totalCount= 0;

for(A *a in allObjects)
{
    NSInteger countOfB = [a.B count];
    NSInteger countOfc = [a.C count];
    totalCount = totalCount + (countOfB * countOfc);
}