Pavan
Pavan

Reputation: 18508

How to update attribute everytime a new object is added in CoreData?

I have a core data model that looks like this: Core data model

Notice both the total attribute and array relationships in both the MonthlyYearSale and PCSParticularProduct entities; with their relationships between the other entities following a one-to-many relationship.

Just a further note:

The PCSParticularProduct entity's total attribute stores the total sale figure made in a particular product id across the month.

The MonthlyYearSale entity's total attribute stores the total monthly sale based on a collection of total sales calculated from a set of 24 or so products across that month.

Question:

When I add a child object in the parent entity's array, how can I update the total attribute on that same parent? I have two entities in which I wish to update the total figure based on the objects added into the array relationship attribute. Is there an efficient way of doing this?

Upvotes: 0

Views: 249

Answers (2)

pickwick
pickwick

Reputation: 3154

You could create a wrapper method in your managedObject subclass like

- (void) insertChild:(NSManagedObject *)object {

call core data method to add the object (or set the object's parent)
update total
}

Or you could use KVC to observe changes to the child array and respond by updating the total. I would recommend the wrapper approach since it does not require that the parent be instantiated.

Upvotes: 1

Lucas van Dongen
Lucas van Dongen

Reputation: 9858

You shouldn't be using CoreData fields to manage those values as they're calculated values. There's nothing to win by saving them unless you have thousands of objects and counting over and over becomes a performance problem. But by then you wouldn't be using CoreData anymore but rather SQLite directly.

You could implement the total like follows:

.h:

@property (readonly) int total

.m

- (int)total;
{
     int subTotal = 0;
     for (ProductSale sale in self.arrayOfChildren)
     {
          subTotal = subTotal + sale.value;
     }

     return subTotal;
}

It will work as a property but it will give you the actual value every time. I'm pretty sure it needs all objects to be read into memory, if this is not the case you should look further into Core Data aggregation:

How to count in coredata (aggregation)?

I woul suggest that if you need a lot of SQL-like functions on your data like aggregates you should investigate if direct usage of SQLite would be a better options. CoreData over SQL is more for storing your models in a related way, not an actual database:

http://www.objc.io/issue-4/SQLite-instead-of-core-data.html

Perhaps you could do a mix of both approaches but I don't know how it would work out if you would access the same DB via CD and directly at the same time.

Upvotes: 0

Related Questions