字典是由键-值对组成的数据集合。通过key(键),查找的对应的value(值),key通常是字符串对象,也可以是其他任意类型对象。在一个字典对象中,key的值必须是唯一的。此外,字典对象的键和值不可以为空(nil),如果需要在字典中加入一个空值,可以加入NSNull对象。
1.字典存储数据的优势
a.方便查找
b.方便删改
2.如何创建一个字典
NSDictionary *dic1 = [NSDictionary dictionary];
NSDictionary *dic1_ = [[NSDictionary alloc] init];
NSDictionary *dic2 = [NSDictionary dictionaryWithDictionary:dic];
NSDictionary *dic2_ = [[NSDictionary alloc] initWithDictionary:dic];
//初始化一个键值对
NSDictionary *dic3 = [NSDictionary dictionaryWithObject:xw forKey:@"小王"];
//创建拥有多个键值对的字典
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:@[xw, zs, ls] forKeys:@[@"xiaowang", @"zhangsan", @"lisi"]];
NSLog(@"%@", dic4);
3.获取字典键值对个数
NSLog(@"%ld",dic5.count);
4.获取所有的键keys(字符串对象);
NSArray *allKeys = [dic5 allKeys];
5.获取所有的value
NSArray *allValues = [dic5 allValues];
6.遍历一个字典
for(NSString *key in allKeys){
NSLog(@"key=%@:value=%@", key, [dic5 objectForKey:key]);
}
7.通过key获取对应的value
NSArray *tempArray = [dic5 objectForKey:@"man"];
NSMutableDictionary
1.创建可变字典
NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithCapacity:0];
2.添加键值对
[mDic setObject:@"Pxd" forKey:@"name"];
[mDic setObject:pArray forKey:@"man"];
[mDic setObject:@"红楼梦" forKey:@"名著"];
NSLog(@"%@", mDic);
3.更改某个键对应的值
[mDic setObject:@"hongloumeng" forKey:@"名著"];
4.删除键值对
//[mDic removeObjectForKey:@"名著"];
//[mDic removeObjectsForKeys:@[@"man", @"nb", @"hel"]];
[mDic removeAllObjects];