1. 字典类型的常用处理

//---------------不可变字典

//1.字典的创建

NSArray *array1 = [NSArray arrayWithObjects:@"zhangsan",@"zhangfei",nil];

NSArray *array2 = [NSArray arrayWithObjects:@"lisi",@"liping", nil];

//第一元素:key:@“zhang"   value:array1

//第二元素:key: @"li:      value:array2

NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:array1,@"zhang",array2,@"li", nil];

NSUInteger count = dic1.count; //字典元素个数

NSLog(@"count:%d",count);

//创建字典时初始化一个元素

NSDictionary *dic2 = [NSDictionary dictionaryWithObject:array1 forKey:@"zhang"];

NSLog(@"dic2 = %@",dic2);

//2.获取字典中所有的key

NSArray *allKeys = [dic1 allKeys]; //dic1.allKeys.

NSLog(@"allKeys= %@",allKeys);

//3.获取字典中所有的value

NSArray *allValues = [dic1 allValues];

NSLog(@"allValues = %@",allValues);

//4.通过key取得value

NSArray *array3 = [dic1 objectForKey:@"zhang"];

NSLog(@"array3 = %@",array3);

//------------字典中优化的方法

NSDictionary *dic3 = @{@"zhang": array1,@"li":array2};

NSLog(@"dic3 = %@",dic3);

//取value的语法:字典[”key“]

NSArray *array4 = dic3[@"zhang"]; //等价于:NSArray *array3 = [dic3 objectForKey:@"zhang"];

NSLog(@"array4 = %@",array4);

//--------------可变字典

//1.创建一个可变字典

NSMutableDictionary *md1 = [[NSMutableDictionary alloc] initWithCapacity:3];

//2.添加元素

[md1 setObject:array1 forKey:@"zhang"];

[md1 setObject:array2 forKey:@"li"];

NSLog(@"md1 = %@",md1);

//将字典dic1 中所有的元素添加到md1字典中

[md1 addEntriesFromDictionary:dic1];

NSLog(@"md1 = %@",md1);

//        [md1 setObject:@"zhangsan" forKey:@"zhang"]; //如果添加相同的key,会将原来的Value覆盖掉

//3.删除(根据key删除元素)

[md1 removeObjectForKey:@"zhang"];

NSLog(@"md1 = %@",md1);

//删除所有元素(清空)

//[md1 removeObjects];

//        //根据多个key删除对应的多个元素

//        [md1 removeObjectsForKeys:@[@"zhang",@"li"]];

//        NSLog(@"md1 = %@",md1);

//---------------------遍历字典

//1.快速遍历

for (NSString *key in md1) {

NSArray *name = [md1 objectForKey:key];

NSLog(@"快速遍历:key = %@,value = %@",key,name);

}

//2.普通遍历

NSArray *allKeys2 = [md1 allKeys];

for (int i = 0; i<allKeys.count - 1; i++) {

NSString *key = allKeys2[i];

NSArray *name = md1[key];

NSLog(@"普通遍历:key = %@,value = %@",key,name);

}

05-07 15:48