2012-06-20 48 views
0

再次卡在Obj-C中的KVCs上。使用跨越n鍵的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 

欣賞任何指針:)

回答

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"]; 
+0

我在想,也許這種方法將是最簡單的。如果沒有人在第二天採取更好的做法,我會接受是正確的。謝謝 :) –