字典:
key ----> value
索引 ----> 文字内容
里面存储的东西都是键值对2. NSMutableDictionary
3. 遍历
key ----> value
索引 ----> 文字内容
里面存储的东西都是键值对
1. NSDictionary
字典的创建:
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"]; // 第一种
<pre name="code" class="objc">// 第二种
NSArray *keys = @[@"name", @"address"];
NSArray *objects = @[@"jack", @"北京"];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
<pre name="code" class="objc">// 第三种
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"jack", @"name",
@"北京", @"address",
@"32423434", @"qq", nil];
<pre name="code" class="objc">// 第四种
NSDictionary *dict = @{@"name" : @"jack", @"address" : @"北京"};
利用索引获取内容、字典的输出:
id obj = [dict objectForKey:@"name"];
id obj = dict[@"name"];
NSLog(@"%@", obj);
// 返回的是键值对的个数
NSLog(@"%ld", dict.count);
2. NSMutableDictionary
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// 添加键值对
[dict setObject:@"jack" forKey:@"name"];
[dict setObject:@"北京" forKey:@"address"];
[dict setObject:@"rose" forKey:@"name"];
//NSMutableDictionary *dict = @{@"name" : @"jack"};
//[dict setObject:@"rose" forKey:@"name"];
// 移除键值对
// [dict removeObjectForKey:(id)];
NSString *str = dict[@"name"];
//NSLog(@"%@", str);
NSLog(@"%@", dict);
3. 遍历
// 字典不允许有相同的key,但允许有相同的value(Object)
// 字典的无序的
NSDictionary *dict = @{
@"address" : @"北京",
@"name" : @"jack",
@"name2" : @"jack",
@"name3" : @"jack",
@"qq" : @"7657567765"};
NSArray *keys = [dict allKeys];
<pre name="code" class="objc">//第一种:
for (int i = 0; i<dict.count; i++)
{
NSString *key = keys[i];
NSString *object = dict[key];
NSLog(@"%@ = %@", key, object);
}
//第二种:
[dict enumerateKeysAndObjectsUsingBlock:
^(id key, id obj, BOOL *stop) {
NSLog(@"%@ - %@", key, obj);
// *stop = YES;
}];
4. 集合总结:
1.NSArray\NSMutableArray
* 有序
* 快速创建(不可变):@[obj1, obj2, obj3]
* 快速访问元素:数组名[i]
2.NSSet\NSMutableSet
* 无序
3.NSDictionary\NSMutableDictionary
* 无序
* 快速创建(不可变):@{key1 : value1, key2 : value2}
* 快速访问元素:字典名[key]