0

再次卡在 Obj-C 中的 KVC 上。

我想使用 KVC 来找到多个键的最小值。

考虑以下数组:

NSArray *data = [[NSArray alloc] initWithObjects:
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:2.0], @"a", [NSNumber numberWithFloat:5.0], @"b", [NSNumber numberWithFloat:4.0], @"c", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:3.0], @"a", [NSNumber numberWithFloat:1.0], @"b", [NSNumber numberWithFloat:1.5], @"c", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:9.0], @"a", [NSNumber numberWithFloat:7.0], @"b", [NSNumber numberWithFloat:6.0], @"c", nil],
                 nil];

我可以通过以下方法轻松找到“a”、“b”或“c”的最小值:

float minKeyA = [[data valueForKeyPath:@"@min.a"] floatValue];  // value: 2.0
float minKeyB = [[data valueForKeyPath:@"@min.b"] floatValue];  // value: 1.0
float minKeyC = [[data valueForKeyPath:@"@min.c"] floatValue];  // value: 1.5

我想要实现的是获取键的 NSSet 或 NSArray 并在这些键的池中找到最小值。

NSSet *keySet1 = [NSSet setWithObjects:@"a", @"b", nil]; 
// use to find absolute minimum value across keys 'a' and 'b' --> desired value 1.0
NSSet *keySet2 = [NSSet setWithObjects:@"a", @"c", nil];
// use to find absolute minimum value across keys 'a' and 'c' --> desired value 1.5
NSSet *keySet3 = [NSSet setWithObjects:@"a", @"b", @"c", nil];
// use to find absolute minimum value across keys 'a', 'b', and 'c' --> desired value 1.0

感谢任何指针:)

4

1 回答 1

1

一个天真的解决方案是首先找到每个键的最小值,然后在第二步中找到这些最小值中的最小值。

NSMutableSet *localMinima = [NSMutableSet setWithCapacity:[keySet1 count]];
for (NSString *key in keySet1) {
    NSString *keyPath = [NSString stringWithFormat:@"@min.%@", key];
    NSNumber *localMin = [data valueForKeyPath:keyPath];
    [localMinima addObject:localMin];
}
NSNumber *globalMin = [localMinima valueForKeyPath:@"@min.self"];
于 2012-06-20T14:30:14.947 回答