iOS OC C

常见类(二)

920 发布: 2015/10/29 05:35 本文总阅读量

创建字典的方式

NSDictionary*dictionary1 = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
NSLog(@"dictionary1:%@",dictionary1);

NSDictionary*dictionary2 = [[NSDictionary alloc]initWithObjects:@[@"v1",@"v2",@"v3"] forKeys:@[@"k1",@"k2",@"k3"]];
NSLog(@"dictionary2:%@",dictionary2);

NSDictionary *dictionary3 = [NSDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2", nil];
NSLog(@"dictionary3:%@",dictionary3);
自己封装一个包含学生信息的字典
NSString *stu_name=@"Tom";
NSArray *stu_score=@[@90,@100,@80];
NSArray *valueArray=@[@20,stu_name,stu_score];
NSDictionary *stuDic=[NSDictionary dictionaryWithObjects:valueArray forKeys:@[@"age",@"name",@"score"]];
NSLog(@"%@",stuDic);
根据已有字典创建新的字典
NSDictionary *dictionary4=[NSDictionary dictionaryWithDictionary:dictionary3];
NSLog(@"dictionary4:%@",dictionary4);
获取字典中所有元素(键值对)的个数
NSDictionary *dictionary4=[NSDictionary dictionaryWithDictionary:dictionary3];
NSLog(@"dictionary4.count=%ld",dictionary4.count);
根据key值去获取value值
NSArray *value1= [dictionary4 valueForKey:@"k1"];
NSLog(@"value1:%@",value1);
NSArray *value_array=[stuDic valueForKey:@"score"];
NSLog(@"value_array:%@",value_array);
获取字典中所有的key
NSArray *keyArray =[dictionary4 allKeys];
NSArray *valueArray1= [dictionary4 allValues];
NSLog(@"keyArray:%@ valueArray1:%@",keyArray,valueArray1);
字典操作
NSMutableDictionary *mutableDic1=[NSMutableDictionary dictionaryWithObjects:@[@"v1",@"v2",@"v3",] forKeys:@[@"k1",@"k2",@"k3",]];

//添加:
[mutableDic1 setObject:@"v4" forKey:@"k4"];
NSLog(@"%@",mutableDic1);

//根据已存在的字典添加
[mutableDic1 addEntriesFromDictionary:dictionary4];
NSLog(@"mutableDic1=%@",mutableDic1);

//修改
//将当前字典所有元素替换成新的字典中的元素

NSDictionary *dictionary =[NSDictionary dictionaryWithObjects:@[@"A",@"B"] forKeys:@[@"A1",@"B1"]];
[mutableDic1 setDictionary:dictionary];
NSLog(@"mutableDic1=%@",mutableDic1);

//指定key值修改
[mutableDic1 setObject:@"newA" forKey:@"A1"];
NSLog(@"%@",mutableDic1);

//删除
[mutableDic1 removeObjectForKey:@"B1"];//指定一个key删除
[mutableDic1 removeObjectsForKeys:@[@"A1",@"B1"]];//指定多个key删除
[mutableDic1 removeAllObjects];//删除所有
NSLog(@"mutableDic1=%@",mutableDic1);