——Java培训、Android培训、iOS培训、.Net培训——–
1、NSDictionary介绍
NSDictionary 的作用类似:通过一个key,就能找到对应的value。它是不可变的,一旦初始化完毕,其内容就无法被修改
而且字典是无序的。
2、创建
//NSDictionary介绍与使用
//1)创建字典,一旦创建,内容就不可改变
//空字典
NSDictionary *dic1 = [NSDictionary dictionary];
//2)创建只有一个键值对的字典
NSDictionary *dic2 = [NSDictionary dictionaryWithObject:@"Amos" forKey:@1];
NSLog(@"dic2 = %@",dic2);
//3)创建有多个键值对的字典
//【注意】字典的key和value都必须是OC对象不能是基础数据类型
//方式一:NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"Amos",@"Allen",@"Andy", nil]forKeys:[NSArray arrayWithObjects:@"1",@"2",@"3", nil]];
//方式二:
NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"Amos",@"1",@"Allen",@"2", nil];
NSLog(@"dic1 = %@",dic3);
//4)快速创建字典
//@{key:vaule}
NSDictionary *dic4 = @{@1: @"Amos",@2: @"Allen",@3: @"Andy"};
NSLog(@"dic1 = %@",dic4);
3、字典的特点
1)字典的key是不能重复的,如果重复了将不会被添加到字典
2)键值对存储数据是无序的
3)键值对集合可以根据key快速获取数据
4、基本用法
1)获取地点键值对个数,即字典长度
- (NSUInteger)count;
例如:
NSUInteger count = dic4.count;
2)根据key值去value
NSString *name = [dic4 objectForKey:@1];
NSLog(@”name = %@”,name);
5、字典的遍历
NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"Amos",@"2", @"Allen",@"3", @"Andy", nil];
//遍历字典
//1)普通方法:先获取key,再根据key获取value
for (NSString *key in dic4) {
NSLog(@"key = %@ value = %@",key,[dic4 objectForKey:key]);
}
//2)block遍历
[dic4 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"key = %@ value = %@",key,obj);
}];
2015-10-08 12:00:53.410 DictionaryDemo[3832:303] key = Amos value = 1
2015-10-08 12:00:53.412 DictionaryDemo[3832:303] key = Allen value = 2
2015-10-08 12:00:53.413 DictionaryDemo[3832:303] key = Andy value = 3
2015-10-08 12:00:53.413 DictionaryDemo[3832:303] key = Amos value = 1
2015-10-08 12:00:53.414 DictionaryDemo[3832:303] key = Allen value = 2
2015-10-08 12:00:53.414 DictionaryDemo[3832:303] key = Andy value = 3