Search code examples
iosobjective-ckvc

Can valueForKeyPath compute the maximum of sums?


I have the following Objective-C class:

@interface GraphDataPoint : NSObject
@property NSDate *date;
@property NSNumber *value;
@end

Given an NSArray of GraphDataPoint, I know how to calculate the maximum value using

[data valueForKeyPath:@"@max.value"]

Now I want to change value to an array of values:

@property NSArray *values;

Is there a similar way to compute the maximum of the sum of the value property of each GraphDataPoint in an NSArray using valueForKeyPath? (I know I can write a nested loop to work it out manually.)


Solution

  • You should be able to do it like this:

    NSArray *a = @[
        [[GraphDataPoint alloc] initWithVal:@[@1, @2, @3]] // Sum=6
    ,   [[GraphDataPoint alloc] initWithVal:@[@4, @1, @1]] // Sum=6
    ,   [[GraphDataPoint alloc] initWithVal:@[@5, @4, @7]] // Sum=16
    ,   [[GraphDataPoint alloc] initWithVal:@[@6, @8, @9]] // Sum=23 <<== Max
    ,   [[GraphDataPoint alloc] initWithVal:@[@7, @6, @2]] // Sum=15
    ];
    
    NSNumber *res = [a valueForKeyPath:@"@[email protected]"];
    NSLog(@"Res: %@", res); // This prints 23