一 字典
1. NSDictionary 不可变字典,继承自 NSObject,字典中存储的元素都是以键值对形式存在的,key 值是唯一的,不能重复.
2. 字典中存储的元素都是无序的.
3. 字典中存储的都是 key/value,这种形式称之为键值对.
4. 便利构造器创建字典
NSDictionary *dic = [NSDictionary dictionary]; //空字典
创建一个空字典
NSDictionary * dic=[[NSDictionary alloc]init]; //是一个空字典
打印字典的标志是一对大括号
5. 字典创建并初始化(dictionWithObjectsAndKeys)
NSDictionary*dic = [[NSDictionaryalloc]initWithObjectsAndKeys:
@”xiaoming”,@”name”,@”18”,@”age”,@”man”,@”sex”,nil];
注意:
1⃣ 创建的是时候 value 值在前, key 值在后;(@”value1”,@”key1”)
2⃣ 字典是无序的
3⃣ 字典创建的时候都是以nil结束
4⃣ value 必须是对象,key值一般是字符串
6. 字典的访问
1⃣ 通过 key值访问value值(objectForKey 和 valueForKey)
NSString *str = [dic objectForKey:@”age”];
NSString *str = [dic valueForKey:@”age”];
2⃣ 获取所有的value的值(allValues)
NSArray *value = [dic allValues];
3⃣ 获取所有的 key值的属性(allKeys)
NSArray *key = [dic allKeys];
4⃣ 获取字典中键值对的个数(count)
NSUInteger count = [dic count];
7. 遍历字典
1⃣ for(NSInteger i = 0;i < count;i++){
//[dic allkeys]返回一个数组 然后使用 ObjectAtIndex 取出数组中的元素
NSString *str = [[dic allkeys]objectAtIndex:i];
NSStirng *value = [dic objectForKey:str];
}
2⃣ for(NSString *key in [dic allKeys]){
NSLog(@”%@ =%@”,key,[dic objectForKey:key]);
}
3⃣ 快速枚举的是字典中的key值
for(NSString *key in dic){
NSLog(@”%@ = %@”,key,[dic objectForKey:key]);
}
二 NSMutableDictionary
1. 可变字典,继承自NSDictionary
2. 初始化
NSMutableDictionary*mDic=[[NSMutableDictionaryalloc]initWithCapacity:0];
3. 向可变数组中添加对象(setObject: forKey:)
[mDic setObject:@”chenyixun” forKey:@”Singer”];
4. 修改key值对应的 value的值(setObject: froKey:或者setValue: forKey:)
[mDic setObject:@”liudehua” forKey:@”Singer”];
5. 删除键值对(removeObjectForKey:)
[mDic removeObjectForKey:@”Duboer”];
6. 清空字典(removeAllObjects)
[mDic removeAllObjects];