你的位置:首页 > 操作系统

[操作系统][oc学习日记]字典


 1     //字典的创建 2     NSDictionary *d1 = [NSDictionary dictionary]; 3     //将创建的字典的内容设置为制定的文件的内容 4     NSString *path = @"";//文件路径 5     NSDictionary *d2 = [NSDictionary dictionaryWithContentsOfFile:path]; 6     //创建具有一个键值的字典 7     NSDictionary *d3 = [NSDictionary dictionaryWithObject:@"s" forKey:@"s"]; 8     //创建具有多个键值的字典 键值对必需对应 9     //值在前 键在后10     NSDictionary *d4 = [NSDictionary dictionaryWithObjectsAndKeys:@"ss",@"2",11                     @"ss",@"1",12                      nil];13     14     //利用数组创建字典15     NSArray *key = @[@"2",@"3",@"4"];16     NSArray *obj = @[@"ss",@"ff",@"gg"];17     NSDictionary *d5 = [NSDictionary dictionaryWithObjects:obj forKeys:key];18     //便捷方式19     //键在前 值在后20     NSDictionary *d6 = @{21               @"2":@"d",22               @"3":@"d"};23     24     //init初始化25     //将初始化的字典内容设置为指定文件内容26     NSDictionary *dd = [[NSDictionary alloc]initWithContentsOfFile:path];27     //初始化具有多个键-值的字典(利用数组)28     NSDictionary *dd1 = [[NSDictionary alloc]initWithObjects:obj forKeys:key];29     //初始化具有多个键-值的字典30     NSDictionary *dd2 = [[NSDictionary alloc]initWithObjectsAndKeys:31     @"ss",@"2",32     @"ss",@"1", nil];33     34     35     36     //字典基本操作37     //字典是无序的 键不可以重复 值可以重复38     //返回所有键39     NSLog(@"%@",[dd2 allKeys]);40     //返回所有值41     NSLog(@"%@",[dd2 allValues]);42     //返回所有值对应的键43     NSLog(@"%@",[dd2 allKeysForObject:@"ss"]);44     //返回对应键的值 最常见 最重要45     NSLog(@"%@",[dd2 objectForKey:@"ss"]);46     //键值对47     NSLog(@"%zi",dd2.count);48 49     50     //不可变字典51     //创建52     NSMutableDictionary *dic = [NSMutableDictionary dictionary];53     //分配空间54     NSMutableDictionary *dic1 = [[NSMutableDictionary alloc]initWithCapacity:10];55     //创建并赋值56     NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"ss",@"2",57                   @"ss",@"1", nil];58     //添加键值对59     [dic2 setObject:@"s" forKey:@"sdads"];60     //删除所有键值对61     [dic2 removeAllObjects];62     //删除指定键对应的键值对63     [dic2 removeObjectForKey:@"sd"];64     65     66     //字典的遍历67     //快速遍历68     for (id key in dic2) {69       NSLog(@"%@ = %@",key,[dic2 objectForKey:key]);70     }71     //代码块遍历72     [dic2 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {73       NSLog(@"%@ %@",key,obj);74     }];75     //迭代器遍历76     //可以输出键和值77     NSEnumerator *en = [dic2 keyEnumerator];//将所有键装入数组78     id key2 = nil;79     while (key2 = [en nextObject]) {80       NSLog(@"%@ %@",key2,[dic2 objectForKey:key2]);81     }82     NSEnumerator *en1 = [dic2 objectEnumerator];//将所有值装入数组83     //只可以输出值84     id obj3 = nil;85     while (obj3 = [en1 nextObject]) {86       NSLog(@"%@", obj);87     }88     89     90     //键给空值会异常  值给控制就是结束标志

补充一点:

如果将自定义的类对象封装进字典 

可以用setValuesForKeysWithDictionary方法对对象属性进行赋值,但是封装进字典的键一定要和类中的属性名相同,并且数量不能超过类中的属性数量