IOS的​​NSDictionary低平均高

问题描述:

现在,我把我的NSDictionary和运行的所有值的找到低,高,计算平均水平。IOS的​​NSDictionary低平均高

由于我是IOS我想问是否有更好的方法来做到这一点。在那儿? 谢谢

+1

编辑你的问题并粘贴你的代码。 – 2012-02-21 17:36:01

这个问题的确切答案取决于你的NSDictionary中的对象类型。一般的答案是,你可以使用Key-Value Coding操作符来做你想做的事情。这里是一个例子:

NSNumber *one = [NSNumber numberWithInt:1]; 
NSNumber *two = [NSNumber numberWithInt:2]; 
NSNumber *three = [NSNumber numberWithInt:3]; 

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:one, @"apple", two, @"orange", three, @"pear", nil]; 
NSLog(@"The max number is %@", [[dictionary allValues] valueForKeyPath:@"@max.intValue"]); 
NSLog(@"The min number is %@", [[dictionary allValues] valueForKeyPath:@"@min.intValue"]); 
NSLog(@"The mean is %@", [[dictionary allValues] valueForKeyPath:@"@avg.intValue"]); 

这可能没有比自己枚举事物更有效率,但它更简洁。

如果您的NSDictionary的内容是具有NSNumber属性的自定义类的对象,则仍然可以通过将属性名称放置在@avg之后(例如, @avg.myProperty。请注意,这些valueForKeyPath方法返回NSNumbers。

没有比通过枚举字典已经完成的更好的方法来做到这一点。这主要是因为NSDictionary包含不透明的对象。他们可能是NSString s,他们可能是NSNumber s或他们可能是CHZLolCat s。他们可以是任何东西。因此,采用低,高和平均的方法并不合理,因为并非每件事都有低,高和平均的概念。

但是,如果您向我们展示了一些代码,我们可能能够就实际的枚举方法提供具体的建议。