字典
2019-02-19 本文已影响0人
习惯了_就好
/*
字典是以键值对的形式来存储数据的
字典里可以存储任意类型数据
字典里存储的数据顺序是不确定的
不可变字典里相同的key,后面的key-value无效;可变字典里相同的key会覆盖以前的值
*/
//不可变数组
//创建字典
NSDictionary * dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"name",@"zhangsan", nil];
NSLog(@"dic1为:%@",dic1);
//便捷方式创建字典
NSDictionary * dic2 = @{@"name":@"lisi",@"age":@"14",@"height":[NSNumber numberWithInt:170],@"dic1":dic1,@"age":@"40"};
NSLog(@"dic2为:%@",dic2);
//获取字典的长度
NSLog(@"dic的长度为:%ld",dic2.count);
//获取字典中的值
NSString * str = [dic2 objectForKey:@"name"];
NSLog(@"dic2中key为name的值是%@",str);
//遍历字典
NSArray * keys = [dic2 allKeys];
for (int i = 0; i<keys.count; i++) {
NSLog(@"%@ = %@",keys[i],[dic2 objectForKey:keys[i]]);
}
NSEnumerator * enumerator =[dic2 objectEnumerator];
id value;
while (value = [enumerator nextObject]) {
NSLog(@"value = %@",value);
}
//可变数组
//创建可变数组
NSMutableDictionary * mutableDic1 = [[NSMutableDictionary alloc]initWithCapacity:0];
//向可变数组添加元素
[mutableDic1 setObject:@"wangwu" forKey:@"name"];
[mutableDic1 setObject:@"男" forKey:@"sex"];
[mutableDic1 setObject:@"nv" forKey:@"sex"];
NSLog(@"可变数组mutableDic1:%@",mutableDic1);
//删除元素
[mutableDic1 removeObjectForKey:@"sex"];
NSLog(@"可变数组mutableDic1:%@",mutableDic1);
//删除所有元素
[mutableDic1 removeAllObjects];
NSLog(@"可变数组mutableDic1:%@",mutableDic1);