Objective-C中字典類

來源:互聯網
上載者:User

標籤:

字典是用於儲存具有映射關係(key-value對)的資料集合.一個key-value對認為是一個條目(Entry),字典是儲存key-value對的容器.

字典類的特點

與數組不同,字典靠key存取元素;

key值不能重複,value必須是對象;

索引值對在字典中是無序儲存的.

字典分為不可變字典(NSDictionary)和可變字典(NSMutableDictionary).

不可變字典(NSDictionary)

字典一旦建立,索引值對不可更改,不可添加, 不可刪除.

僅能讀取key或value.

建立字典對象

1 NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"張三" forKey:@"name"];2 NSLog(@"dic1 %@", dic1);

建立有多個key-value對的字典

1 NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"a", @"1", @"b", @"2", @"c", @"3", nil];2 NSLog(@"dic2 %@", dic2);3 //擷取所有的key4 NSLog(@"key %@", dic2.allKeys);5 // 擷取所有的value6 NSLog(@"value %@", dic2.allValues);7 // 通過key 找 value8 // 根據key擷取對應value9 NSLog(@"object %@", [dic2 objectForKey:@"2"]);

可變字典(NSMutableDictionary)

建立可變字典

1 NSMutableDictionary *mDic = [NSMutableDictionary dictionary];2 [mDic setObject:@"lilei" forKey:@"name"];3 [mDic setObject:@"m" forKey:@"sex"];4 NSLog(@"mDic %@", mDic);

添加/修改key-value對

1 // 當key不存在的時候 添加key-value對2 // 當key存在的時候 找到對應的key 替換對應value內容3 [mDic setObject:@"lilei" forKey:@"name"];4 [mDic setObject:@"male" forKey:@"sex"];5 NSLog(@"mDic %@", mDic);6 // 修改7 [mDic setObject:@"hanmeimei" forKey:@"name"];8 NSLog(@"mDic %@", mDic);

刪除字典

1 // 刪除2 [mDic removeObjectForKey:@"name"];3 NSLog(@"mDic %@", mDic);

遍曆字典

 1 // 遍曆字典 2 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"lilei", @"name", @"male", @"sex", @"18", @"age", nil]; 3 NSLog(@"dic %@", dic); 4 NSArray *arr1 = dic.allKeys; 5 for (NSInteger i = 0; i < arr1.count; i++) { 6 // 擷取每一個key值 7 NSString *key = [arr1 objectAtIndex:i]; 8 // 根據key擷取對應value 9 NSLog(@"key: %@, value: %@", key, [dic objectForKey:key]);10 }

 

Objective-C中字典類

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.