NSArray *aa = [NSArray arrayWithObjects:@"11", @"122", nil]; NSLog(@"%@", aa); //里面只有一对键值的字典 NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"2134" forKey:@"id"]; NSLog(@"%@", dic1); //多个键值的字典 NSArray *value =[NSArray arrayWithObjects:@"2134", @"迅雷", @"hudeifeifei", nil ]; //字典中, 是无序的 。。。 NSArray *key = [NSArray arrayWithObjects:@"id", @"topic", @"tfr",nil ]; NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:value forKeys:key]; NSLog(@"%@", dic2); NSArray *value1 = [NSArray arrayWithObjects:@"xiyouji",@"hongloumeng",@"shuihuzhuan",@"sanuoyanyi", nil]; NSArray *key1 = [NSArray arrayWithObjects:@"guoguanzhong",@"wuchengen",@"ximenqi",@"caocao", nil]; NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:value1 forKeys:key1]; NSLog(@"%@", dic3); [dic3 objectForKey:@"xiyouji"]; // NSLog(@"------%@", dic3); //字典长度 NSLog(@"%lu",[dic3 count]); //调出所有的key值 NSArray *allkey = [dic3 allKeys]; NSLog(@"%@", allkey); NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:@"aa", @11, @"bb", @22, @"cc", @"33", nil];//value-key value-key @11--- 字面量,--语法糖 NSLog(@"%@", dic4); //可变字典bobo NSMutableDictionary *bobo = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Cyuyan", @"bobo", nil]; NSLog(@"%@", bobo); //插入两个键值 [bobo setObject:@"xing" forKey:@"xiaoliu"]; [bobo setObject:@"UI" forKey:@"laojiang"]; NSLog(@"%@", bobo); //插入一个键值 [bobo setValue:@"OC" forKeyPath:@"xiaoyunzi"]; NSLog(@"---------》%@",bobo); //对bobo对值践行修改 [bobo setObject:@"sisheng" forKeyedSubscript:@"bobo"]; NSLog(@"1111111%@",bobo); //使用forin遍历字典所有的key for (NSString *i in bobo) { NSLog(@"%@",[bobo objectForKey:i]); } // NSInteger count1 = [bobo count]; // for (int i = 1; i < count1; i++) { // NSLog(@"......%@", [bobo objectForKey:i]); // } //有问题。。。问题 // NSArray *allKeys = [bobo allKeys]; // for (int i = 0; i < [bobo count]; i++) { // NSString *key = [allKeys objectsAtIndexes:i]; // NSString *valu = [bobo objectForKey:key]; // NSLog(@"%@",key, valu); // } //移除xiaoliu和其对应的值 [bobo removeObjectForKey:@"xiaoliu"]; NSLog(@"%@", bobo); //移除所有 // [bobo removeAllObjects]; // NSLog(@"%@", bobo); //移除数组定义的key和其对应的值 NSArray *re =[NSArray arrayWithObjects:@"bobo",@"xiaoyunzi", nil]; //里面都是key [bobo removeObjectsForKeys:re]; NSLog(@"%@",bobo);
字典简介:
- 字典类用于保存具有映射关系(key-value对)的数据
- 一个key-value对认为是一个元素(实体),字典是存贮key-value对的容器
字典类的特点
- 于数组不同,数组靠下标存取数据,数据的下标是唯一的
- 字典靠key存取元素,key不能重复(如果重复只输出第一个,而第二个没有实际意义),value必须是对象
- 键值对在字典中是无序存储的,,,,
NSDictionary
- 不可变字典
- 字典一旦创建,键值对就不可更改,不可添加,不可删除
- 仅能读取key或者value
NSDictionary常用用法
时间: 2024-12-29 15:49:57