1.字典的创建
/*
字典:保存数据的一种工具
分类:不可变字典、可变字典
详情:通过键(key)-值(value)的形式存储数据
注意:
1、value可以相同,key必须唯一
2、字典保存对象类型
3、key一般为字符串
4、字典中的多个key-value是没有顺序的
*/
不可变字典
//创建空字典
NSDictionary *dic1 = [NSDictionary dictionary];
NSDictionary *dic2 = [[NSDictionary alloc] init];
//对像方法创建
NSDictionary *dic3 = [[NSDictionary alloc] initWithObjectsAndKeys:@"sunck", @"1", @"is", @"2", @"a", @"3", @"good", @"4", @"man", @"5", nil];
NSLog(@"dic3 = %@", dic3);
//注意:前后两个数组(数据,键值)一一对应的
NSDictionary *dic4 = [[NSDictionary alloc] initWithObjects:@[@"sunck", @"is", @"a", @"good", @"man"] forKeys:@[@"1", @"2", @"3", @"4", @"5"]];
//通过已存在的字典创建新的字典
NSDictionary *dic5 = [[NSDictionary alloc] initWithDictionary:dic4];
//类方法:
NSDictionary *dic6 = [NSDictionary dictionaryWithObjectsAndKeys:@"sunck", @"1", @"is", @"2", @"a", @"3", @"good", @"4", @"man", @"5", nil];
NSDictionary *dic7 = [NSDictionary dictionaryWithObjects:@[@"sunck", @"is", @"a", @"good", @"man"] forKeys:@[@"1", @"2", @"3", @"4", @"5"]];
NSDictionary *dic8 = [NSDictionary dictionaryWithDictionary:dic4];
//注意:键值之间用:链接,多个键值对用,分隔,最后省略了nil
NSDictionary *dic9 = @{@"1": @"sunck", @"2": @"is", @"3": @"a", @"4": @"good", @"5": @"man"};
不可变字典的其他方法
//取值
NSDictionary *dic1 = @{@"1": @"sunck", @"2": @"is", @"3": @"a", @"4": @"good", @"5": @"man", @"6": @"Oh", @"7": @"he", @"8": @"is", @"9": @"good"};
NSLog(@"dic1 = %@", dic1);
//取一个值
NSString *str = [dic1 objectForKey:@"3"];
NSString *str2 = dic1[4];
//取多个值
NSArray * arr1 = [dic1 objectsForKeys:@[@"1",@"2",@"3"] notFoundMarker:@"NotFound"];
//取s所有的值
NSArray *value = [dic1 allValues];
//取所有的key
NSArray *key = [dic1 allKeys];
//取出所有value对应的key
NSArray *key3 = [dic1 allKeysForObject:@"sdd"];
//遍历字典
//针对字典来说,in的前面是字典中的key
//in的后面是要遍历的集合(数组、字典)
for (NSString *key in dic1) {
NSString *value = [dic1 objectForKey:key];
}
//枚举遍历
NSEnumerator *emumer = [dic1 keyEnumerator];
id keyString = nil;
while (keyString = [emumer nextObject]) {
NSString *value = [dic1 objectForKey:keyString ];
}
2.可变字典的增删改查
//增
NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithObjects:@[@"sun", @"is", @"a", @"good", @"man"] forKeys:@[@"1", @"2", @"3", @"4", @"5"]];
//增加一个键值对
[mutDic setObject:@"sdf" forKey:@"7"];
//增加多个键值对,
//注意:如果增加时,键值对键一样,原数据会被修改为当前数据
[mutDic addEntriesFromDictionary:@{@"6":@"sdf",@"3":@"sdf"}];
//删
[mutDic removeObjectForKey:@"6"];
//删除多个
[mutDic removeObjectsForKeys:@"6",@"5"];
//删除所有的
[mutDic removeAllObjects];
//改
NSMutableDictionary *mutDic3 = [[NSMutableDictionary alloc] initWithObjects:@[@"sunck", @"is", @"a", @"good", @"man", @"!"] forKeys:@[@"1", @"2", @"3", @"4", @"5", @"6"]];
[mutDic3 setObject:@"nice" forKey:@"4"];
NSLog(@"mutDic3-1 = %@", mutDic3);
[mutDic3 setValue:@"handsome" forKey:@"4"];
NSLog(@"mutDic3-2 = %@", mutDic3);
//将字典替换为后面的字典
[mutDic3 setDictionary:mutDic1];
网友评论