NSDictionary
字典,由键值对组成,通过一个key(键), 就能找到对应的value(值) 。
是不可变的, 一旦初始化完毕, 里面的内容就无法修改
注意:
1. 字典存储的时候,必须是"键值对"的方式来存储(同时键不要重复,虽然重复也不报错)
2. 键值对中存储的数据是"无序的".
3. 键值对集合可以根据键, 快速获取数据.
NSDictionary的创建
+ (instancetype)dictionary;
+ (instancetype)dictionaryWithObject:(id)object forKey:(id <NSCopying>)key; //objectForKey,根据键取值。
+ (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
//定义一个有一组键值对的字典
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"first" forKey:@"1"];
NSLog(@"%@",dict);
/*
{
1 = first;
}
*/
快速创建字典
NSDictionary *dict = @{@"1" : @"first", @"2" : @"two", @"3" : @"three"};
NSLog(@"%@",dict);
/*
{
1 = first;
2 = two;
3 = three;
}
*/
- (NSUInteger)count;
返回字典的键值对数目
NSDictionary *dict = @{@"1" : @"first", @"2" : @"two", @"3" : @"three"};
//获取字典的键值对的个数
NSUInteger count = [dict count];
NSLog(@"%lu",count); //3
- (id)objectForKey:(id)aKey;
根据key取出value
NSDictionary *dict = @{@"1" : @"first", @"2" : @"two", @"3" : @"three"};
//通过KEY获取Value
NSString *str = [dict objectForKey:@"2"];
NSLog(@"%@",str); //two
NSDictionary遍历方法
1)快速遍历
NSDictionary *dict = @{@"1" : @"first", @"2" : @"two", @"3" : @"three"};
//快速遍历
for (NSString *key in dict) {
//此时遍历的是 dict 中得 KEY 值,需要 Value 值的时候调用对象的 objectForKey 方法
NSLog(@"%@------>%@",key,[dict objectForKey:key]);
}
结果
2015-10-07 13:17:59.596 字典[2388:152702] 1------>first
2015-10-07 13:17:59.597 字典[2388:152702] 2------>two
2015-10-07 13:17:59.597 字典[2388:152702] 3------>three
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {}];
NSDictionary *dict = @{@"1" : @"first", @"2" : @"two", @"3" : @"three"};
//block块的遍历 键 值 是否停止
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@\t%@",key,obj);
}];