如何从包含字典的NSArray中获取最大值?

cmd*_*cmd 8 iphone cocoa-touch objective-c key-value-coding nsarray

你如何从带有字典的NSArray中获得最大的价值?

假设我有NSArray包含带有"年龄","姓名"等字典的词典.现在我想得到年龄最大的记录.这有可能与一些KVC魔术?或者我是否必须以"手动"的方式进行迭代?

我尝试过类似的东西:

int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue];
Run Code Online (Sandbox Code Playgroud)

Dav*_*ist 15

除非"intValue"是你词典中的一个键,否则关键路径不会有多大好处.

如果它是你应该使用的最大年龄@"@max.age"(在字典上)来获得它.对于词典中的任何其他键也是如此.

[myDictionary valueForKeyPath:@"@max.age"];
Run Code Online (Sandbox Code Playgroud)

如果numbers是值数组,则可以将其@"@max.self"用作获取最大值的关键路径.

[myArrayOfNumbers valueForKeyPath:@"@max.self"];
Run Code Online (Sandbox Code Playgroud)

  • 对我有用,可变或不可变.`NSArray*numbers = @ [@ 3,@ 5,@ 2.5,@( - 5)]; NSMutableArray*mutable = [NSMutableArray arrayWithArray:numbers]; NSNumber*largestValue = [数字valueForKeyPath:@"@ max.self"]; NSNumber*largestValueFromMutable = [mutable valueForKeyPath:@"@ max.self"];`给出正确的结果,没有崩溃. (2认同)