一、NSDictionary
1> NSDictionary(字典)通常在给定一个关键字(通常是一个NSString字符串)下存储一个数值(可以是任何类型的对象)。然后你可以使用这个关键字查找相应的数值;2> NSDictionary
key ---->value
索引 ---->文字内容
里面存储的东西都是键值对
3> 常用方法:
//NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"];
NSArray *keys = @[@"name",@"address"];
NSArray *objects = @[@"jack",@"北京"];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
id obj = [dict objectForKey:@"address"];
NSLog(@"%@",obj);
/*
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"jack",@"name",@"北京",@"address", nil];
*/
NSDictionary *dict = @{@"name" : @"jack",@"address" : @"北京"};
//id obj = [dict objectForKey:@"address"];
id obj = dict[@"name"];
NSLog(@"%@",obj);
注意编译器特性所带来的代码简化
二、NSMutableDictionary
1> 创建新的NSMutableDictionary对象,向类NSMutableDictionary发送dictionary消息;2> NSMutableDictionary继承自NSDictionary;
3> NSMutableDictionary可变字典,NSDictionary不可变字典;
4> 常用方法:
添加键值对\元素:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//添加键值对
[dict setValue:@"Jack" forKey:@"name"];
[dict setValue:@"北京" forKey:@"address"];
注意
[dict setValue:@"rose" forKey:@"name"];
执行该代码之后Jack会被覆盖;
移除键值对
[dict removeObjectForKey:<#(id)#>]
字典的打印
NSString *str = dict[@"name"];
NSLog(@"%@",str);
键值 = 对象
三、字典的遍历
for循环
NSDictionary *dict = @{
@"address" : @"北京",
@"name" : @"jack",
@"name2" : @"jack",
@"name3" : @"jack",
@"qq" : @"7657567765"};
/NSArray *keys = [dict allKeys];
for (int i = 0; i<dict.count; i++)
{
NSString *key = keys[i];
NSString *object = dict[key];
NSLog(@"%@ = %@", key, object);
}
注意字典是无序的
字典不允许有相同的key,但允许有相同的value(object)
block
NSDictionary *dict = @{
@"address" : @"北京",
@"name" : @"jack",
@"name2" : @"jack",
@"name3" : @"jack",
@"qq" : @"7657567765"};
[dict enumerateKeysAndObjectsUsingBlock:(id key, id obj, BOOL *stop) {
NSLog(@"%@ - %@", key, obj);
// *stop = YES;
四、集合的总结
集合1.NSArray\NSMutableArray
* 有序
* 快速创建(不可变):@[obj1, obj2, obj3]
* 快速访问元素:数组名[i]
2.NSSet\NSMutableSet
* 无序
3.NSDictionary\NSMutableDictionary
* 无序
* 快速创建(不可变):@{key1 : value1, key2 : value2}
* 快速访问元素:字典名[key]
集合小补充,看懂
NSArray *persons = @[
@{@"name" : @"jack", @"qq" : @"432423423", @"books": @[@"5分钟突破iOS编程", @"5分钟突破android编程"]},
@{@"name" : @"rose", @"qq" : @"767567"},
@{@"name" : @"jim", @"qq" : @"423423"},
@{@"name" : @"jake", @"qq" : @"123123213"}
];
//
// NSDictionary *jim = persons[2];
//
NSString *bookName = persons[0][@"books"][1];
NSLog(@"%@", bookName);
//NSArray *array = persons[0][@"books"];
//NSLog(@"%@", array);
// 先取出1位置对应的字典
// 再取出字典中qq这个key对应的数据
//NSLog(@"%@", persons[1][@"qq"]);
// NSLog(@"%@", jim);