//字典
//初始化一个字典
//注意:字典中所装的数据类型:对象类型,不可以是基本数据类型
//字典是无序的
//key通常是字符串, key必须唯一
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"value", @"key", @"value1", @"key1", nil];
NSLog(@"dic is %@", dic);
//创建空的字典
NSDictionary *nullDic = [NSDictionary dictionary];
NSLog(@"nullDic is %@", nullDic);
//创建Person对象
Person *zhangsan = [[Person alloc] init];
zhangsan.name = @"张三";
zhangsan.age = 100;
Person *lisi = [[Person alloc] init];
lisi.name = @"李四";
lisi.age = 400;
Person *wangwu = [[Person alloc] init];
wangwu.name = @"王五";
wangwu.age = 500;
//创建一个数组
NSArray *names = @[zhangsan, lisi, wangwu];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:
@"v1", @"k1",
@"v2", @"k2",
@"v3", @"k3",
names, @"k4", nil];
NSLog(@"dic2 is %@", dic2);
//从字典中取值,如果这个key不存在,则返回NULL
NSString *str1 = [dic2 objectForKey:@"k1"];
NSString *str2 = [dic2 objectForKey:@"k2"];
NSString *str3 = [dic2 objectForKey:@"k5"];
NSLog(@"str1 is %@", str1);
NSLog(@"str2 is %@", str2);
NSLog(@"str3 is %@", str3);
//取出字典中的数组中的第一个元素的姓名
// NSArray *arr = [dic2 objectForKey:@"k4"];
// Person *ps = [arr objectAtIndex:0];
//嵌套调用
Person *ps = [[dic2 objectForKey:@"k4"] objectAtIndex:0];
NSLog(@"ps name is %@", ps.name);
//字典中的键值对个数
NSInteger count = dic2.count;
NSLog(@"count is %ld", count);
//取出字典中所有的key
NSArray *keys = [dic2 allKeys];
NSLog(@"keys is %@", keys);
//取出字典中所有的value
NSArray *values = dic2.allValues;
NSLog(@"values is %@", values);
//字典的快速创建和取值
NSDictionary *dic3 = @{@"k1": @"v1",
@"k2": @"v2",
@"k3": @"v3"};
NSString *v1 = dic3[@"k1"];
NSLog(@"dic3 is %@", dic3);
NSLog(@"v1 is %@", v1);
//可变字典
//初始化空的字典
NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
//给字典预期的空间
// NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithCapacity:10];
//添加元素
[dic1 setObject:@"value1" forKey:@"key1"];
[dic1 setObject:@"value2" forKey:@"key2"];
[dic1 setObject:@"value3" forKey:@"key3"];
NSLog(@"dic1 is %@", dic1);
//设置键值对,如果key已经存在,则是修改key所对应的value,如果不存在,则创建一个新的键值对
[dic1 setObject:@"value6" forKey:@"key6"];
NSLog(@"dic1 is %@", dic1);
//删除元素
[dic1 removeObjectForKey:@"key6"];
NSLog(@"dic1 is %@", dic1);
//删除所有元素
[dic1 removeAllObjects];
NSLog(@"dic1 is %@", dic1);
//字典的遍历
NSDictionary *dic = @{@"k1": @"v1",
@"k2": @"v2",
@"k3": @"v3",
@"k4": @"v4",
@"k5": @"v5"};
NSArray *keys = [dic allKeys];
//遍历字典---传统遍历
for (int i = 0; i < dic.count; i++) {
//获取key
NSString *key = [keys objectAtIndex:i];
NSString *value = [dic objectForKey:key];
NSLog(@"key:%@----value:%@", key, value);
}
NSLog(@"-------------优美的分割线-------------------");
//快速遍历
//拿到的是key
for (id key in dic) {
//循环块
id value = [dic objectForKey:key];
NSLog(@"key:%@----value:%@", key, value);
}