Foundation中的字典(NSDictionary,NSMutableDictionary)是由键-值对组成的数据集合.正如,我们在字典里查找单词的定义一样,通过key(键),查找的对应的value(值),key通常是字符串对象,也可以是其他任意类型对象.在一个字典对象中,key的值必须是唯一的.此外,字典对象的键和值不可以为空(nil),如果需要在字典中加入一个空值,可以加入NSNull对象。
简单的使用代码如下:
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //1、用一个或多个键值对初始化一个字典对象: 以值,建,值,键,...,nil的顺序 //不可变字典 NSDictionary *dic01=[[NSDictionary alloc] initWithObjectsAndKeys:@"key0",@"value0",@"key1",@"value1",@"key2",@"value2", nil]; NSLog(@"dic01:%@",dic01); //2.用两个数组初始化一个字典,一个key数组,一个value数组,两个数组大小必须相等,否则Crash NSArray *keyArray=@[@"name0",@"name1",@"name2"]; NSArray *valueArray=@[@"hong",@"wang",@"zhao"]; NSDictionary *dic02=[[NSDictionary alloc]initWithObjects:keyArray forKeys:valueArray]; NSDictionary *dic2=[[NSDictionary alloc]initWithObjects:valueArray forKeys:keyArray]; NSLog(@"dic02:%@",dic02); NSLog(@"dic2:%@",dic2); //3、用一个数据字典初始化另一个数据字 NSDictionary *dict03=[[NSDictionary alloc] initWithDictionary:dic01]; NSDictionary *dict3=[NSDictionary dictionaryWithDictionary:dic01]; NSLog(@"dict03:%@",dict03); NSLog(@"dict3:%@",dict3); //4.字典对象的创建和保存-文件 // [dict3 writeToFile:@"/Users/moonvan2006/Desktop/new/tesk.txt" atomically:YES]; NSDictionary *dict4=[NSDictionary dictionaryWithContentsOfFile:@"/Users/moonvan2006/Desktop/new/tesk.txt"]; NSLog(@"dict4:%@",dict4); //字典对象元素的访问 //1、分别获取字典的所有键、值 NSArray *allkeys=[dic01 allKeys]; NSLog(@"allkeys:%@",allkeys); NSArray *allvalues=[dic01 allValues]; NSLog(@"allvalues:%@",allvalues); //2、通过指定的key取对应的value对象,没有这个key的话.返回nil NSString *num1 = [dic01 objectForKey:@"value1"]; NSNumber *num2 = [dic01 objectForKey:@"key5"]; NSLog(@"%@",num1); NSLog(@"%@",num2); //3、获取字典中键值对的个数 NSUInteger paircount=[dic2 count]; NSLog(@"%lu",paircount); //4.字典的遍历 for(id key in dic01){ id value=[dic01 objectForKey:key]; NSLog(@"%@=%@",key,value); } //可变数据字典 NSMutableDictionary *mDict1=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"aaa",@"name0",@"bbb",@"name1",@"ccc",@"name2", nil]; NSLog(@"%@",mDict1); //1、加入元素到NSMutableDictionary中 (注意:当key值中存在要添加的键值对中的key值时,则添加,否则覆盖) [mDict1 setObject:@"ddd" forKey:@"name3"]; [mDict1 setObject:@"eee" forKey:@"name1"]; NSLog(@"add: %@",mDict1); //2、查看 中所有元素个数: NSLog(@"%lu",mDict1.count); NSNumber *num3 =[mDict1 objectForKey:@"name1"]; NSLog(@"%@",num3); NSNumber *num4 = [mDict1 objectForKey:@"name10"]; NSLog(@"%@",num4); //3、添加其他NSMutableDictionary [mDict1 setValuesForKeysWithDictionary:dic01]; NSLog(@"++++%@",mDict1); //4、根据key值删除 [mDict1 removeObjectForKey:@"name1"]; NSLog(@"---%@",mDict1); //5、删除所有 [mDict1 removeAllObjects]; NSLog(@"%@",mDict1); } return 0; }