1、创建做一个字典类似对象
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"snms",@"1",@"tony",@"2",nil ]
//其中,snms和tony是value,1和2是key,key是唯一的;
2、获取字典中的值
NSString *key = @"2";
NSString *val = [ dic objectForKey:key ];
NSLog(@"%@",val);
3、快速创建字典
NSDictionary *dic = @{@"1":@"snms",@"2":@"tony"}
//1为key,snms为val
4、遍历字典
1、枚举遍历
NSEnumerator *enu = [ dic KeyEnumerator]; //遍历key
NSEnumerator *enu = [ dic objectEnumerator]; //遍历val
id obj;
while (obj = [enm nextObject])
{
NSLog(@"%@",obj);
}
2、for in遍历
id obj;
for(obj in dic){
NSLog(@"%@",obj); //默认得到的是键;
NSLog(@"%@",[dic objectForKey:obj]); //这样就得到值了
}
5、可变字典
5.1 创建一个可变字典
NSMutableDictionary *md = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"val",@"key",nil ];
5.2 创建一个空字典【常用】
NSMutableDictionary *md = [[NSMutableDictionary alloc]init]
5.3设置字典的值【常用】
[md setObject:@"val" forKey:@"key"];
//key是唯一的,如果在设置中有重复的key,那么后面的值会覆盖前面的值;
5.4 删除字典中的值
[ md removeObjectForKey:@"1" ];
网友评论