字典Dictionary

字典没有顺序可言

key  -  Value

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

不可变字典

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

1、字典存储数据的优势

  a、方便查找

  b、方便删改

2、如何创建一个字典

     NSDictionary *dic = @{@"小王":xw, @"张三":zs, @"李四":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"]];

        NSLog(@"%@", dic4);

 

3、获取字典键值对个数

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

 

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

  NSArray *allKeys = [dic5 allKeys];

5、获取所有的value

  NSArray *allValues = [dic5 allValues];

6、遍历一个数组

  for(NSString *key in allKeys){

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

  }

7、通过key获取对应的value

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

 

NSMutableDictionary  可变字典

1、创建可变字典

  NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithCapacity:0];

2、添加键值对

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

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

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

 

3、更改某个键对应的值

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

4、删除键值对

      [mDic removeObjectForKey:@"名著"];

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

          [mDic removeAllObjects];

posted @ 2015-12-24 10:36  赵鹏s  阅读(175)  评论(0编辑  收藏  举报