Foundation 框架初体验
1. NSDictionary 不可变字典
//常用方法 a=1 b=2 c=3 key在前 value在后
NSDictionary *dict2 =@{@"a":@"1",@"b":@"2",@"c":@"3"}; a = 1 b = 2
从 NSDictionary 取值的时候有两个方法,objectForKey: 和 valueForKey:
字典和数组的区别
1.字典的内存不是连续的 数组是连续的
2.用key和value进行对应(键值)kvc键值编码 (数组是下标)
3.字典的输出为 {} 数组的输出为()
不可变的字典 要赋值 申明之后就不能改了
// 对应 a=1 b=2 c=3 key在后 value在前
NSDictionary *dict =[NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:@"1",@"2",@"3",nil] forkeys:[NSArray arrayWithObjects:@"a",@"b",@"c",nil]];
NSDictionary *dict3 =[NSDictionary dictionaryWithObjectsAndKeys:@“ddd”,@“1”, @“eee”,@“2”, @“off”,@“3”, @“gig”,@“4”,] 1 = ddd 2 = eee
// 根据value 找 key
NSArray *array = [dict allKeysForObject:@“jjj”];
//键值对的数量
int count =(int)[dict count];
//根据key 取值value
NSString *value = [dict valueForKey:@"b"];
NSString *value = [dict objectForKey:@"b"]; //这两个方法都一样
//取得数组中所有 键值对 中的 value
NSArray *allValues =[dict allValues]; // 结果 1 2 3
//取得数组中所有 键值对 中的 key
NSArray *allKeys =[dict allKeys]; // 结果 a b c
//如果没有相应的key d 就返回数组 not found 提示
NSArray *array =[dict objectsForKey:[NSArray arrayWithObjects:@"a",@"b",@"d",nil] notFoundMarker:@"not found"];
//遍历字典 用 for in 常用 (不管你用什么方式遍历 遍历的都是字典的key 而不是字典的value)
for(NSString *key in dict)
{
NSString *str =[dict objectForKey:str]; // 根据key 把 字典中的值取出
//输出结果为 a=1 b=2 c=3
NSLog(@"%@ = %@",key , [dict objectForKey:key]);
}
2. NSMutableDictionary 可变字典
NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
//添加键值对
[dict setObject:@"1" forkey:@"a"];
[dict setObject:@"2" forkey:@"b"];
[dict setObject:@"3" forkey:@"c"];
//删除所有键值对
[dict removeAllObjects];
//删除指定的键值对
[dict removeObjectForKey:@"b"];
//删除多个键值对
[dict removeObjectsForKeys:[NSArray arrayWithObjects:@"a",@"b",@"c",nil] ];
快速遍历
[dict enumerateKeysAndObjectsUsingBlock:^(id key,id obj , BOOL *stop )]{
NSLog(@"key = %@,value = %@",key, obj);
}];