字典dictionary

不可变词典NSDictionary

字典没有顺序可言,键值对

Key-Value

键(字符串对象)-值(对象)

0.字典里面多个键值对的值可以相同,但是键不能相同,必须唯一

1.字典存储的优势

  a.方便查找

  b.方便删改

2.如何创建一个字典

  NSDictionary *dic = @{@"小王":xw,@"张三":zs,@"ls":ls};

  NSDictionary *dic1 = [NSDictionary dictionary];

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

        NSDictionary *dic2 = [NSDictionary dictionaryWithDictionary:dic];

        NSDictionary *dic2_ = [[NSDictionary alloc]initWithDictionary:dic];

初始化一个键值对

       NSDictionary *dic3 = [NSDictionary dictionaryWithObject:xw forKey:@"小王"];

创建拥有多个键值对的字典

        NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:@[xw,zs,ls] forKeys:@[@"xiaowang",@"zhangsan ",@"lisi "]];

 3.获取字典键值对个数

NSLog(@"count:%ld",dic5.count);

4,获取所有的键keys(字符串对象)

NSArray*allKeys = [dic5 allKeys];

5,获取所有的value 

NSArray *allValues = [dic5 allValue];

6.遍历一个字典

for (NSString *key in allkeys){

NSLog(@"key = %@:value = %@",key,[dic5 objectForKey:key]);

}

7,通过key获取对应的value 

NSArray *tempArray = [dic5 objectForKey:@"man"]);

NSMubtableDictionary

1.创建可变字典

NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithCapacity:0];

2.添加键值对

[mDic setObject:@"yql" forKey:@"name"];

        [mDic setObject:pArray forKey:@"man"];

        [mDic setObject:@"红楼梦" forKey:@"名著"];

        NSLog(@"7.%@",mDic);

3.更改某个键对应的值

        [mDic setObject:@"hongloumeng" forKey:@"名著"];

4.删除键值对

        [mDic removeObjectsForKeys:@"名著"];

       [mDic removeObjectsForKeys:@[@"man",@"nb",@"hel"]];

        [mDic removeAllObjects];

        NSLog(@"8..%@",mDic);

 

posted @ 2015-12-24 20:59  蜗牛才是大牛  阅读(282)  评论(0编辑  收藏  举报