core data derivation expression key path uses an operator as an intermediate component

1k Views Asked by At

I'm trying to write the derivation expression for the sum of a to many relationship attribute.

I have an item and a group, the item has a price and total price (amount * price). I want to write an expression for the total price for the group as the sum of its components.

enter image description here

When I build I get the error

error: Misconfigured Property: LAEItemGroup.totalPrice key path “[email protected]” uses an operator as an intermediate component

according to the documentation and the WWDC 2019 Making Apps with Core Data it should be possible to get the sum on a to many relationship.

Could someone please help me find the correct syntax or way to do so.

As a work around I tried to write a var that worked in that class as so

@objc
public var totalPrice: Double {
    value(forKeyPath: "[email protected]") as? Double ?? 0
}

so why the KeyPath value works but not in the model editor?

3

There are 3 best solutions below

2
On BEST ANSWER

I've now had an opportunity to check. It seems the format used by the model editor is for the aggregate operator to be at the end of the expression (which as you point out, is different from the format used in other expressions):

items.totalPrice.@sum
2
On

I just finished a WWDC Core Data lab with Rishi who helped me with this! You should use sum:(items.totalPrice) instead of the .@sum syntax. The parentheses syntax can also be used for some other functions (e.g. count:(items) (the number of items in the to-many relationship) or max:(items.createdAt) (the date of the most recent item)).

2
On

Use items.totalPrice.@sum as the derived property's expression in Xcode's model editor.

This only looks to work for numeric types though? I have a property maxDate with a derived property expression of

items.createdAt.@max

It compiles but throws an error at runtime:

'NSInvalidArgumentException', reason: 'currently unsupported (too many steps)

Where Date is the data type for createdAt