Foundation - NSDictionary
/*
集合
1.NSArray\NSMutableArray //ArrayList
* 有序
* 快速创建(不可变):@[obj1, obj2, obj3]
* 快速访问元素:数组名[i]
2.NSSet\NSMutableSet //Set
* 无序
* 不可以快速创建
3.NSDictionary\NSMutableDictionary //Map
* 无序
* 快速创建(不可变):@{key1 : value1, key2 : value2}
* 快速访问元素:字典名[key]
*/
/*
字典:
key ----> value
索引 ----> 文字内容
里面存储的东西都是键值对
*/
// NSDictionary
// NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"];
// NSArray *keys = @[@"name", @"address"];
// NSArray *objects = @[@"jack", @"北京"];
// NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:
@"jack", @"name",
@"北京", @"address",
@"32423434", @"qq", nil];
NSDictionary *dict = @{@"name" : @"jack", @"address" : @"北京"};
// id obj = [dict objectForKey:@"name"];
id obj = dict[@"name"];
// 返回的是键值对的个数
NSLog(@"%ld", dict.count);
// NSMutableDictionary
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// 添加键值对
[dict setObject:@"jack" forKey:@"name"];
[dict setObject:@"北京" forKey:@"address"];
[dict setObject:@"rose" forKey:@"name"];
// 移除键值对
// [dict removeObjectForKey:@"name"];
NSString *str = dict[@"name"];
NSLog(@"%@", dict);
NSMutableDictionary *dict = @{@"name" : @"jack"};
[dict setObject:@"rose" forKey:@"name"];
// 字典不允许有相同的key,但允许有相同的value(Object)
// 字典是无序的
NSDictionary *dict = @{
@"address" : @"北京",
@"name" : @"jack",
@"name2" : @"jack",
@"name3" : @"jack", //将替换前面重复的Key
@"qq" : @"7657567765"};
// 1.遍历 NSDictionary
// NSArray *keys = [dict allKeys];
//
// for (int i = 0; i<dict.count; i++)
// {
// NSString *key = keys[i];
// NSString *object = dict[key];
//
//
// NSLog(@"%@ = %@", key, object);
// }
// 2.遍历 NSDictionary
[dict enumerateKeysAndObjectsUsingBlock:
^(id key, id obj, BOOL *stop) {
NSLog(@"%@ - %@", key, obj);
// *stop = YES;
}];
// 取值
NSArray *persons = @[
@{@"name" : @"jack", @"qq" : @"432423423", @"books": @[@"5分钟突破iOS编程", @"5分钟突破android编程"]},
@{@"name" : @"rose", @"qq" : @"767567"},
@{@"name" : @"jim", @"qq" : @"423423"},
@{@"name" : @"jake", @"qq" : @"123123213"}
];
NSString *bookName = persons[0][@"books"][1];
NSLog(@"%@", bookName);