天天看點

Foundation 之 NSDictionary和NSMutableDictionaryNSDictionary字典NSMutableDictionary可變字典

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

注意:字典中的鍵值對是不講究順序的。