/*_______________不可变字(NSDictionary)____________*/ //1.字典的创建 //值(value) NSArray *array1 = @[@"zhangsan",@"zhangfei",@"zhangchaoyang"]; //zhang NSArray *array2 = @[@"lisi",@"lining",@"lilei"]; //li //两个元素:zhang:array1 li:array2 NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:array1,@"zhang",array2,@"li", nil]; // NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:<#(nonnull id), ...#>, nil] NSLog(@"dic1:%@",dic1); //通过已有的字典给现在的字典初始化 NSDictionary *dic2 = [[NSDictionary alloc] initWithDictionary:dic1]; NSLog(@"dic2:%@",dic2); //2.获取字典中的元素个数 NSUInteger count = dic1.count; NSLog(@"count:%ld",count); //3.获取字典中的所有key(键) NSArray *keys = [dic1 allKeys]; NSLog(@"key:%@",keys); //4.获取所有的value(值) NSArray *values = [dic1 allValues]; NSLog(@"values:%@",values); //5.通过key取得对应的value NSArray *value = [dic1 objectForKey:@"zhang"]; NSLog(@"value:%@",value); //注意:在字典中key唯一,但是value可以相同 NSDictionary *dic3 = [[NSDictionary alloc] initWithObjectsAndKeys:array1,@"zhang",array2,@"li",array1,@"li1", nil]; NSLog(@"%@",dic3); /*____________________优化语法___________________________*/ //初始化 NSDictionary *dic4 = @{ @"zhang":array1, @"li":array2 }; NSLog(@"dic:%@",dic4); //根据key获取vlaue NSArray *v = dic4[@"zhang"]; NSLog(@"v:%@",v); /*______________可变字典(NSMutableDictionary)________*/ //创建可变字典 NSMutableDictionary *mutDic1 = [[NSMutableDictionary alloc] initWithCapacity:5]; //1.添加元素 // [mutDic1 setObject:array1 forKey:@"zhang"]; // [mutDic1 setObject:array2 forKey:@"li"]; //注意:如果在添加键值对的时候,如果添加了已有的key,则会覆盖以前的数据 // [mutDic1 setObject:@"liyoubing" forKey:@"li"]; //将dic1中的所有键值对添加到mutDic1 [mutDic1 addEntriesFromDictionary:dic1]; //2.删除 //删除所有元素 // [mutDic1 removeAllObjects]; //根据key删除 // [mutDic1 removeObjectForKey:@"li"]; //根据多个key删除数据 // [mutDic1 removeObjectsForKeys:@[@"li",@"zhang"]]; NSLog(@"mutDic1:%@",mutDic1); //----------字典的遍历---------- //方式一 //获取所有的key NSArray *keyArray = mutDic1.allKeys; for (int i=0; i<keyArray.count; i++) { //1.获取指定的key NSString *key = keyArray[i]; //2.根据key->value // mutDic1 objectForKey:<#(nonnull id)#> NSArray *value = mutDic1[key]; NSLog(@"key:%@ value:%@",key,value); } //方式二:快速遍历 for (NSString *key in mutDic1) { //根据key->value NSArray *value = [mutDic1 objectForKey:key]; NSLog(@"key:%@ vlaue:%@",key,value); } /* 字典是无序的 */