//创建字典对象,以键值对的形式存储,字典里键唯一,值可以不唯一,键,值为任意对象,且只能为对象
/***** 直接创建字典 **********/
NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"ab",@" ",@"three",@"3",@"two",@"2", nil];
NSLog(@"第1种方式创建字典%@",dic1);//打印时,大括号是字典,小括号是数组
NSLog(@"%ld",dic1.count);//求字典的长度
//根据键来返回值
id obj = [dic1 objectForKey:@"2"];
NSLog(@"%@",obj);
NSString *str1 = [dic1 objectForKey:@"2"];
NSLog(@"%@",str1);
/** 以2个相同的不可变数组来创建字典 **/
NSArray *arr1 = @[@"one",@"two",@"three"];
NSArray *arr2 = @[@"1",@"2",@"3"];
NSDictionary *dic2 = [[NSDictionary alloc]initWithObjects:arr1 forKeys:arr2];
NSLog(@"第2种方式创建字典%@",dic2);
/*****************************/
NSDictionary *dic3 = @{@"1":@"one",@"2":@"two",@"3":@"three"};
NSLog(@"第3种方式创建字典%@",dic3);
//返回所有的key
NSArray *arr3 = [dic2 allKeys];
NSLog(@"%@",arr3);
//返回所有的value
NSArray *arr4 = [dic2 allValues];
NSLog(@"%@",arr4);
//用快速枚举的方式枚举字典的值
for (NSString *key in dic2)
{
id obj = [dic2 objectForKey:key];
NSLog(@"%@",obj);
}
for (id key in dic2)//系统默认遍历字典里的键
{
id obj = [dic2 objectForKey:key];
NSLog(@"%@",obj);
}
//创建一个空的可变字典
NSMutableDictionary *dic4 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dic5 = [NSMutableDictionary dictionary];
NSLog(@"dic4 = %@",dic4);
NSLog(@"dic5 = %@",dic5);
//创建多个键值对的可变字典
NSMutableDictionary *dic6 =[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three" ,@"3",nil];
NSLog(@"dic6 = %@",dic6);
//添加键值对,若果key存在,表示修改,不存在,表示添加
[dic6 setObject:@"four" forKey:@"4"];
NSLog(@"dic6 = %@",dic6);
//删除键值对
[dic6 removeObjectForKey:@"3"];
NSLog(@"dic6 = %@",dic6);
//删除多个key对应的键值对
NSArray *arr5 = @[@"1",@"2"];
[dic6 removeObjectsForKeys:arr5];
NSLog(@"dic6 = %@",dic6);
//删除所有的键值对
[dic6 removeAllObjects];
NSLog(@"dic6 = %@",dic6);
//重置字典
NSDictionary *newdic = @{@"1": @"one",@"2":@"two"};
[dic6 setDictionary:newdic];
NSLog(@"dic6 = %@",dic6);