2012-02-21 77 views
0

現在,我把我的NSDictionary和運行的所有值的找到低,高,計算平均水平。IOS的​​NSDictionary低平均高

由於我是IOS我想問是否有更好的方法來做到這一點。在那兒? 謝謝

+1

編輯你的問題並粘貼你的代碼。 – 2012-02-21 17:36:01

回答

4

這個問題的確切答案取決於你的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。

0

沒有比通過枚舉字典已經完成的更好的方法來做到這一點。這主要是因爲NSDictionary包含不透明的對象。他們可能是NSString s,他們可能是NSNumber s或他們可能是CHZLolCat s。他們可以是任何東西。因此,採用低,高和平均的方法並不合理,因爲並非每件事都有低,高和平均的概念。

但是,如果您向我們展示了一些代碼,我們可能能夠就實際的枚舉方法提供具體的建議。