1 //字典和可变字典 2 NSDictionary和NSMutableDictionary 3 4 //建立 5 NSDictionary *dict=[[NSDictionary alloc] initWithObjectsAndKeys: 6 @"one",@"1",@"three",@"3",@"two",@"2",nil]; 7 //字典中的元素是以键值对的形式存储的。 8 //@"one"(值=value)和@"1"(键=key)组成了一个键值对 9 //键值对的值和键都是任意对象,可是键每每使用字符串 10 //字典存储对象的地址没有顺序 11 NSLog(@"%@",dict); 12 //结果: 13 //1=one; 14 //2=two; 15 //3=three; 16 17 //枚举法遍历 18 //键的遍历 19 NSEnumerator *enumerator=[dict keyEnumerator]; 20 id obj; 21 while(obj=[enumerator nextObject]){ 22 NSLog(@"%@",obj);//结果:132 23 } 24 //值的遍历 25 NSEnumerator *enumerator=[dict objectEnumerator]; 26 id obj; 27 while(obj=[enumerator nextObject]){ 28 NSLog(@"%@",obj);//结果:one three two 29 } 30 31 32 //快速枚举法 33 for(id obj in dict){ 34 NSLog(@"%@",obj);//遍历的是键 35 NSLog(@"%@",[dict objectForKey:obj]);//获得值 36 } 37 //能够经过下面的语句经过键获得值 38 NSString *str=[dict objectForKey:@"1"]; 39 40 41 [dict release]; 42 43 //可变字典 44 //建立 45 NSMutableDictionary *dict=[[NSMutableDictionary alloc] init]; 46 //添加 47 [dict setObject:@"one" forKey:@"1"]; 48 [dict setObject:@"two" forKey:@"2"]; 49 //删除 50 [dict removeObjectForKey:@"1"]; 51