Reputation: 561
I need to find count of children based on logic.
I have table A, it has two relationship B and C. Now i need to find count of B and C. Count = No of B * NO of C.
Data:
A1
{
{
B1a
},
{
C1a,
C1b
}
},
A2:
{
{
B2a,
B2b
},
{
C2a,
C2b
}
}
Total Count = 6
i have tried with following
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);
}
This is work fine. But when i have 10000 records it is taking more time. Please suggest me if any alternative ways.
Upvotes: 0
Views: 125
Reputation: 119041
Don't do the multiplication on demand. Each time an A
instance has the relationship to B
or C
changed, calculate the product and store it in a new attribute on A
. Now to fetch your total count you can use only a single fetch (returning dictionary type) and then @sum
(using the array with a collection operator) and none of the objects need to actually be loaded into memory.
Consider using KVO to monitor for relationship changes and trigger the update to your product.
Upvotes: 1