Don't fear. Although the set and array operators in KVC are very powerful, I still find myself having to refer to the documentation almost every time I use them in complex key paths like this. Because valueForKeyPath:
is a method, you can call it from the debugger console. I often find that getting the key path right requires setting a breakpoint just before the KVC call and trying some stuff in the debugger console. Python with PyObjC (included in OSX since 10.5) is also a great interactive environment to test/debug KVC keypaths. In this particular example...
@sum
sends the -[NSNumber decimalValue]
message to each item returned by [company valueForKeyPath:@"departments.employees"]
(the "receiving array" in key-value coding language). It thus expects that each item in the receiving array is an NSNumber
. I suspect that company.departments
is a set, thus [company valueForKeyPath:@"departments.employees"]
is a set of sets, not a collection of NSNumbers
. I believe you want to create a "flattened" collection of all the employees, from which you can then calculate the sum:
id allEmployees = [company valueForKeyPath:@"[email protected]"];
NSNumber *totalSalary = [allEmployees valueForKeyPath:@"@sum.salary"];
Assuming each employee is in only one department, the following also appears to work
NSNumber *totalSalary = [company valueForKeyPath:@"[email protected][email protected]"];