A dictionary is a collection of data that holds a mapping relationship (Key-value pairs). A key-value is considered an entry (Entry), and the dictionary is a container for storing key-value pairs.
Features of the Dictionary class
Unlike arrays, dictionaries access elements by key;
The key value cannot be duplicated, and value must be an object;
Key-value pairs are stored in the dictionary in unordered order.
Dictionaries are divided into immutable dictionaries (nsdictionary) and variable dictionaries (nsmutabledictionary).
Immutable Dictionary (nsdictionary)
Once a dictionary is created, key-value pairs cannot be changed, cannot be added, and cannot be deleted.
Only key or value can be read.
Create a Dictionary object
1 nsdictionary *dic1 = [nsdictionary dictionarywithobject:@ " Zhang San " forkey:@ " name"]; 2 NSLog (@ "dic1%@", Dic1);
Create a dictionary with multiple key-value pairs
1Nsdictionary *dic2 = [Nsdictionary Dictionarywithobjectsandkeys:@"a",@"1",@"b",@"2",@"C",@"3", nil];2NSLog (@"Dic2%@", dic2);3 //get all the keys4NSLog (@"Key%@", Dic2.allkeys);5 //get all the value6NSLog (@"value%@", dic2.allvalues);7 //find value by key8 //get the corresponding value based on key9NSLog (@"Object%@", [Dic2 Objectforkey:@"2"]);
Variable dictionary (nsmutabledictionary)
Create a mutable dictionary
1 nsmutabledictionary *mdic = [ Nsmutabledictionary dictionary]; 2 [mDic setobject:@ " lilei forkey:@" name "; 3 [mDic setobject:@ " m forkey:@" sex "; 4 NSLog (@ " mdic%@ , MDic);
Add/Modify Key-value to
1 //add Key-value When key is not present2 //when key is present, find the corresponding key to replace the value content .3[MDic SetObject:@"Lilei"Forkey:@"name"];4[MDic SetObject:@"male"Forkey:@"Sex"];5NSLog (@"MDic%@", mDic);6 //Modify7[MDic SetObject:@"Hanmeimei"Forkey:@"name"];8NSLog (@"MDic%@", MDic);
Delete Dictionary
1 // Delete 2 [mDic removeobjectforkey:@ "name"]; 3 NSLog (@ "mDic%@", MDic);
Traverse Dictionary
1 //Traverse Dictionary2Nsdictionary *dic = [Nsdictionary Dictionarywithobjectsandkeys:@"Lilei",@"name",@"male",@"Sex",@" -",@" Age", nil];3NSLog (@"DiC%@", DIC);4Nsarray *ARR1 =Dic.allkeys;5 for(Nsinteger i =0; i < Arr1.count; i++) {6 //get each key value7NSString *key =[arr1 objectatindex:i];8 //get the corresponding value based on key9NSLog (@"key:%@, Value:%@", Key, [dic Objectforkey:key]);Ten}
Dictionary classes in Objective-c