Question

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:@"accounts.assets.@sum.assetAmount"];
}

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?

Was it helpful?

Solution

This should work:

- (NSDecimalNumber *)totalAssetValue
{
    return [self valueForKeyPath:@"accounts.@sum.assets.@sum.assetAmount"];
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top