Foundation 之 NSDictionary和NSMutableDictionary

来源:互联网 发布:linux最新内核编译 编辑:程序博客网 时间:2024/05/23 19:19

NSDictionary字典


      字典中的元素是以键值对的形式存储的

字典初始化

      NSDictionary * dict = [[NSDictionary alloc] 

         initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3",nil];

            // @"one"和@"1"组成了一个键值对
            // @"one"称为值(value),@"1"称为键(key)
            // 键值对的值和键,都是任意对象,但是键往往使用字符串
            // 字典存储对象的地址没有顺序,字典中不考虑对象的顺序,如果考虑顺序用数组。
      或者:
      NSDictionary * dict = @{
            @"greeting":@"Hello",
            @"farewell":@"Goodbye"
      }

从字典中获取值

      // 与如何从NSArray中获取对象的方式类似

      NSString * str = dict[@"greeting"];

字典遍历

      1.枚举器法

      键的遍历
      NSEnumerator * enumerator = [dict keyEnumerator];
      值的遍历
      NSEnumerator * enumerator = [dict objectEnumerator];
      while(obj = [enumerator nextObject]) {
            NSLog(@"%@", obj);
      }

2.快速枚举法

      for(id obj in dict) {
            NSLog(@"%@", obj);  // 快速遍历法遍历出来的是键。
            NSString * str = [dict objectForKey:obj];  // 通过键可以找到对应的值
            NSLog(@"%@", str);
      }

NSMutableDictionary可变字典


      可变字典类是字典类的子类,所以拥有父类NSDictionary的所有方法,并且增加了自己特有的功能。

可变字典初始化

      NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];

往字典里增加键值对

      [dict setObject:@"one" forKey:@"1"]; 
      [dict setObject:@"two" forKey:@"2"];

通过键,删除指定键值对

      [dict removeObjectForKey:@"1"]; 

删除所有的键值对

      [dict removeAllObjects]; 


注意:字典中的键值对是不讲究顺序的。

0 0
原创粉丝点击