In the previous chapter, we used an enumerator to access and return the key values in the dictionary. Now we can use Quick enumeration to find the corresponding key values.
Methods involved:
Objectforkey:This method means to return a value to the corresponding key. The following two methods are used. For the first time, this method is not used in the loop. The value @ "1 ", the corresponding value is @ "one ".
PS: Here, we find the key, which indicates that the value is found.
The following is an example:
#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) { @autoreleasepool { //字典的快速枚举法和数组里的快速枚举法是一样的. NSDictionary *dicti = [[NSDictionary alloc]initWithObjectsAndKeys:@"One", @"1", @"Three", @"3",@"Two", @"2", nil]; //字典和数组唯一不同的是, 数组要求顺序, 字典不用要求, 而且字典可以快速查找某一个键. //通过键, 我们可以快速的找到值 NSString *str = [dicti objectForKey:@"1"]; NSLog(@"str = %@", str); //快速枚举法 这里会找到键, 找到了键也就是得到了值 for(id obj in dicti) { NSLog(@"key = %@", obj); NSLog(@"object = %@", [dicti objectForKey:obj]); } } return 0;}
Output result:
2014-10-13 21:10:18.844 RapidEnumNSDictionary[6705:303] str = One2014-10-13 21:10:18.845 RapidEnumNSDictionary[6705:303] key = 12014-10-13 21:10:18.845 RapidEnumNSDictionary[6705:303] object = One2014-10-13 21:10:18.846 RapidEnumNSDictionary[6705:303] key = 32014-10-13 21:10:18.846 RapidEnumNSDictionary[6705:303] object = Three2014-10-13 21:10:18.846 RapidEnumNSDictionary[6705:303] key = 22014-10-13 21:10:18.846 RapidEnumNSDictionary[6705:303] object = TwoProgram ended with exit code: 0
Nsdictionary uses the quick Enumeration Method