四、NSDictionary和NSMutableDictionary
1、不可变字典NSDictionary
//字典的创建 NSArray *array1 = [NSArray arrayWithObjects:@”zhangsan”,@”zhangfei”,nil]; NSArray *array2 = [NSArray arrayWithObjects:@”lisi”,@”liping”,nil]; NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:array1,@”zhang”,array2,@”li”,nil]; //获取字典中的元素个数 NSUInteger count = dic1.count;//or [dic1 count] NSLog(@”count = %ld”, count); //创建一个字段是,初始化一个对象 NSDictionary *dict2 = [NSDictionary dictionaryWithObject:array1 forKey:@”zhang”]; //获取字段中所有的key NSArray *allkeys = [dic1 allKeys];//or dic1.allKeys //获取字典中所有的value NSArray *allvalues = [dic1 allValues]; //通过key获取value NSArray *array = [dic1 objectForKey:@”zhang”]; /*------------------------------------------------*/ NSDictionary *dic3 = @{@”zhang”:array1,@”li”:array2}; NSLog(@”dic3 = %@” ,dic3); //取value的语法,字段[“key”] NSArray *array4 = dic3[“@”zhang”]; NSLog(@” array4 =%@” , array4);
2、可变字典NSMutableDictionary
//创建一个可变字典 NSMutableDictionary *md1 = [[NSMutableDictionary alloc] initWithCapacity:3]; //添加元素 [md1 setObject:array1 forKey:@”zhang”]; [md1 setObject:array2 forKey:@”li”]; //将字典dic1中的所有元素添加到md1字典中 [md1 addEntriesFromDictionary:dic1];//字典中相同的key不能重复添加 NSLog(@” md1 = %@” , md1); //如果添加相同的key,会将原来的value覆盖掉 [md1 setObject:@”zhangsan” forKey:@”zhang”]; //删除 [md1 removeObjectForKey:@”zhang”]; //删除所有的元素 [md1 removeAllObjects]; //根据多个key删除对应多个元素 [md1 removeObjectsForKeys:@[@”zhang”,@”li”]; NSLog(@”md1 = %@”, md1); //遍历字典 //快速遍历 for (NSString *key in md1){ NSArray * names = [md1 objectForKey:key]; NSLog(@” names=%@,value=%@”,key, names); } //普通遍历 NSArray *allkeys = [md1 allKeys]; for(int i=0;i< allkeys.count;i++){ NSString *key = allValues[i]; NSArray *names = md1[key]; NSLog(@”key=%@,value=%@”,key,names); }
时间: 2024-11-01 21:21:15