1.字典中的元素是以键值对的形式存储,在键值对中键和值都可以是任何对象,但是键往往是字符串,在字典中存储的对象没有顺序,更改键值对的添加顺序对最后的输出结果没有任何影响。
2.声明一个字典
NSDictionary * dict = [[[NSDictionary alloc] initWithObjectsAndKeys:@"One",@"1",@"three",@"3",@"two",@"2", nil]autorelease]; NSLog(@"新生成的dictionary是:%@",dict);
3.Dictionary 的遍历
3.1.枚举器法遍历dictionary,取值的时候是按照存储的顺序进行遍历的.可以分别遍历键和值
3.1.1.遍历键
NSEnumerator * enumerator = [dict keyEnumerator]; id objKey; while (objKey = [enumerator nextObject]) { NSLog(@"key is :%@",objKey); }
3.1.2.遍历值
NSEnumerator * enumerator = [dict objectEnumerator]; id objKey; while (objKey = [enumerator nextObject]) { NSLog(@"key is :%@",objKey); }
3.2.foreach循环遍历dictionary的键
for(id objkey1 in dict){ NSLog(@"foreach遍历dictionary 取出来的键是:%@",objkey1); //根据键取得dictionary中的值 NSString * value = [dict objectForKey:objkey1]; NSLog(@"根据键取出来的值是:%@",value);}
4.向键值对中添加键和值
NSMutableDictionary * mutableDictionary = [[[NSMutableDictionary alloc] init] autorelease]; [mutableDictionary setObject:@"hello" forKey:@"A"]; [mutableDictionary setObject:@"world" forKey:@"B"]; [mutableDictionary setObject:@"I" forKey:@"C"]; [mutableDictionary setObject:@"love" forKey:@"D"]; [mutableDictionary setObject:@"you" forKey:@"E"]; NSLog(@"mutableDictionary is %@",mutableDictionary);
5.删除键值对 可以根据remove系列方法进行删除
[mutableDictionary removeObjectForKey:@"A"]; NSLog(@"删除后的字符串 mutableDictionary is %@",mutableDictionary);
时间: 2024-10-05 23:50:48