Foundation中的字典是由键-值对组成的数据集合,好比java中的Map,在字典对象中key值必须是唯一的,另外字典对象中的键和值都不能为nil。,如果要在字典对象中表示一个空值,可以用NSNull对象(这里主要指值value)。字典对象也可分为不可变字典和可变字典。
1、不可变字典
NSNumber *num1 = [NSNumber numberWithInt:5]; NSNumber *num2 = [NSNumber numberWithInt:10]; NSNumber *num3 = [NSNumber numberWithInt:15]; //初始化一个字典 NSDictionary *dictionary = [NSDictionary dictionaryWithObject:num1 forKey:@"num"]; //通过键获取值 NSObject *object = [dictionary objectForKey:@"num"]; NSDictionary *moreNum = [NSDictionary dictionaryWithObjectsAndKeys:num1,@"num1", num2,@"num2",num2,@"num3",nil]; //将字典对象的key转化成一个枚举对象,用于遍历 NSEnumerator *enumerater = [moreNum keyEnumerator]; //获取所有的键 NSArray *keyArray = [moreNum allKeys]; //获取所有的值 NSArray *valueArray = [moreNum allValues]; //创建一个新字典,新字典包含其他字典 NSDictionary *newDic = [NSDictionary dictionaryWithDictionary:dictionary]; //获取字典数量 NSInteger *theNum = [newDic count];
同样继承自NSDictionary,所以NSDictionary中的所有方法都适用于他
//创建一个可变字典 NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:num1,@"num1", num2,@"num2",num2,@"num3",nil]; //向可变字典对象中加入整个字典 NSDictionary *dic2 = [NSDictionary dictionaryWithObject:@"nihao" forKey:@"hello"]; [mDic addEntriesFromDictionary:dic2]; //向可变字典中追加一个键值对 [mDic setValue:@"jimGreen" forKey:@"name"]; //遍历对象,取数据 for(id key in mDic){ id obj = [mDic objectForKey:key]; NSLog(@"%@",obj); }