Reputation: 2312
I have a method inside a subclass of an NSManagedObject, which returns the total sum of all assets. Currently it looks like this and works fine
- (NSDecimalNumber *)totalAssetValue
{
NSDecimalNumber *total = [NSDecimalNumber zero];
for (NSManagedObject *account in [self valueForKey:@"accounts"]) {
for (NSManagedObject *asset in [account valueForKey:@"assets"]) {
total = [total decimalNumberByAdding:[asset valueForKey:@"assetAmount"]];
}
}
return total;
}
I would like to use KVC collection operator to eliminate the loops, so I tried this
- (NSDecimalNumber *)totalAssetValue
}
return [self valueForKeyPath:@"[email protected]"];
}
However, I receive the following error
-[__NSSetI decimalValue]: unrecognized selector sent to instance 0x60000000dc70
Do I have the proper syntax to replicate the above loops? or is it something else?
Upvotes: 1
Views: 262
Reputation: 539945
This should work:
- (NSDecimalNumber *)totalAssetValue
{
return [self valueForKeyPath:@"[email protected][email protected]"];
}
Both "accounts" and "assets" are to-many relationships, therefore you need two "@sum" operators (corresponding to the two nested for-loops in your original code).
Note that it not officially documented (as far as I know) that the Key-Value Coding "@sum"
operator returns an NSDecimalNumber
, it might be "just" an NSNumber
.
Upvotes: 2