下面例子是网上流传的,写的很细
NSArray *array1 = [NSArray arrayWithObjects:@"iphone",@"ipod",nil]; NSArray *array2 = [NSArray arrayWithObjects:@"mac",@"imac",@"mac pro",nil]; ////1、创建字典 ,类方法初始化自动释放 NSDictionary *myDictionary = [NSDictionarydictionaryWithObjectsAndKeys:array1,@"mobile",array2,@"computers",nil];//注意用nil结束 NSLog(@”myDictionary = %@”,myDictionary); //得到key-value的个数 int dictSize = [myDictionary count]; //根据key找到字典中的值 NSArray *mobile = [myDictionary objectForKey:@"mobile"]; //得到所有key NSArray *keys = [myDictionary allKeysForObject:array1]; //得到所有value NSArray *values = [myDictionary allValues]; //快速枚举 for(id key in myDictionary) { NSLog(@”key: %@,value: %@”,key,[myDictionary objectForKey:key]); } //如果字典只包含属性列表对象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary)可以保存到文件中 NSString *filePath = [[[NSBundlemainBundle]resourcePath]stringByAppendingPathComponent:@”dict.txt”]; BOOL success = [myDictionary writeToFile:filePath atomically:YES]; //用文件填充 NSDictionary *myDict2 =[NSDictionary dictionaryWithContentsOfFile:filePath]; //可变字典 NSMutableDictionary *dictMutable = [[NSMutableDictionaryalloc]initWithObjectsAndKeys:array1,@”mobile”,array2,@”computer”, nil]; NSString *string4 = @”stringTV”; //修改对象 [dictMutable setObject:string4 forKey:@"media"]; //删除对象 [dictMutable removeObjectForKey:@"mobile"]; //删除多个对象 NSArray *keyArray =[NSArray arrayWithObjects:@"mobile",@"computer", nil]; [dictMutable removeObjectForKey:keyArray]; //删除所有对象 [dictMutable removeAllObjects];