美文网首页iOS 开发
IOS字典(可变、不可变、字典排序)

IOS字典(可变、不可变、字典排序)

作者: 你的小福蝶 | 来源:发表于2016-05-27 08:28 被阅读2182次

NSDictionary(字典)

一、创建字典的方式

1.创建空的字典

NSDictionary *dic1=[[NSDictionary alloc]init];

NSDictionary *dic2=[NSDictionary dictionary];

NSLog(@"%@,%@",dic1,dic2);

2.创建有内容的字典

NSDictionary *dictionary1=[NSDictionary dictionaryWithObject:@"Value"forKey:@"key"];

NSLog(@"%@",dictionary1);

NSDictionary *dictionary2=[[NSDictionary alloc]initWithObjects:@[@"V1",@"V2",@"V3"]forKeys:@[@"K1",@"K2",@"K3"]];

NSDictionary *dictionary3=[NSDictionary dictionaryWithObjectsAndKeys:@"V1",@"K1",@"V2",@"K2",nil];

NSLog(@"%@",dictionary2);

示例:自己封装一个学生信息的字典

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);

3.根据已有字典创建新的字典

NSDictionary *dictionary4=[NSDictionary dictionaryWithDictionary:dictionary3];

4.获取字典中所有元素(键值对)的个数

NSLog(@"dictionary4.count: %ld",[dictionary4 count]);

5.根据Key获取value值

NSString *value1=[dictionary4 valueForKey:@"K1"];

NSLog(@"value1=%@",value1);

NSArray *value_array=[stuDic valueForKey:@"score"];

NSLog(@"%@",value_array);

6.获取字典中所有的Key和value

NSArray *keyArray=[dictionary4 allKeys];

NSArray *value_Array=[dictionary4 allValues];

NSLog(@"%@,%@",keyArray,value_Array);


NSMutableDictionary (可变字典) 

1.创建可变字典(注意:可变字典必须进行开辟空间操作!)

NSMutableDictionary *mutabledic1=[NSMutableDictionary dictionaryWithObjects:@[@"v1",@"v2",@"v3"]forKeys:@[@"k1",@"k2",@"k3"]];

NSLog(@"%@",mutabledic1);

2.添加元素(键值对)

[mutabledic1 setObject:@"v4"forKey:@"k4"];//可以是k3,直接覆盖,所以是set

NSLog(@"%@",mutabledic1);

3.根据已经存在的字典添加

[mutabledic1 addEntriesFromDictionary:dictionary4];

NSLog(@"%@",mutabledic1);

4.修改(update):

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

NSDictionary *dic3=[NSDictionary dictionaryWithObjects:@[@"A",@"B",@"C"]forKeys:@[@"A1",@"A2",@"A3"]];

[mutabledic1 setDictionary:dic3];

NSLog(@"%@",mutabledic1);

//指定Key值修改

[mutabledic1 setObject:@"NewA"forKey:@"A1"];

NSLog(@"%@",mutabledic1);

//删除

[mutabledic1 removeObjectForKey:@"A2"];//指定Key删除

[mutabledic1 removeObjectsForKeys:@[@"A1",@"A2"]];//指定多个Key删除

[mutabledic1 removeAllObjects];//删除所有

}


//给数组进行排序的方法

NSArray *keyArray =[[alldictionary allKeys]sortedArrayUsingSelector:@selector(compare:)];

相关文章

网友评论

    本文标题:IOS字典(可变、不可变、字典排序)

    本文链接:https://www.haomeiwen.com/subject/hggxdttx.html