------iOS training look forward to communicating with you! -------
Today look at the Nsdirctionary class in the foundation framework, Nsmutabledirctionary class, called Dictionary in OC, Dictionary is unordered, this is not the same as Nsarray.
First, Nsdirctionary class
1. How to create
//Creation of dictionariesNsarray *array1 = [Nsarray arraywithobjects:@"Zhangsan",@"Zhangfei", nil Nil]; Nsarray*array2 = [Nsarray arraywithobjects:@"Lisi",@"liping", nil Nil]; //first element: key:@ "Zhang" value:array1//second element: key:@ "li" Value:array2Nsdictionary *dict = [[Nsdictionary alloc] Initwithobjectsandkeys:array1,@"Zhang", Array2,@"Li", nil Nil]; NSLog (@"%@", dict);
As we can see, the creation of the Nsdirctionary class is based on the Nsarray, which needs to be noted at the end: nil
2. Adding elements
storing an element Nsdictionary *dict2 = [nsdictionary dictionarywithobject:array1 forkey:@ "Zhang"];
3. Get key for all elements
// get all the keys Nsarray *allkeys = [Dict AllKeys];
4. Get the value of all elements
// get all the value Nsarray *allvalues = [Dict allvalues];
5. Get Value by key
// get value from key Nsarray *values = [dict objectforkey:@ "Zhang"];
6, Nsdirctionary fast creation way and access way
// optimized Syntax Nsdictionary *dict3 = @{@ "zhangsan": array1,@ "Lisi": Array2}; NSLog (@ "%@", dict3); *array4 = dict3[@ "Zhang"];
Second, Nsmutabledirctionary class
The previous Nsdirctionary class is an immutable dictionary, and there is a corresponding mutable dictionary in the same OC: Nsmutabledirctionary
1. Create a mutable dictionary
// Create a mutable dictionary with a size of 3 Nsmutabledictionary *md1 = [[Nsmutabledictionary alloc] initwithcapacity:3]; *array1 = [[Nsarray alloc] initwithobjects:@ "zhangsan"@ "lis ", nil Nil];
Create a mutable dictionary that can specify its size, of course, when the capacity is full, he automatically expands
2. Adding elements
adding elements [Md1 setobject:array1 Forkey:@ "Zhang"]; *MD2 = [[Nsmutabledictionary alloc] initwithcapacity:3]; [MD2 addentriesfromdictionary:md1];
3. Deleting elements
// Delete element [MD1 Removeobjectforkey:@ "Zhang"]; // Delete with key [Md1 removeallobjects]; // Delete all elements [Md1 Removeobjectsforkeys:array1]; //
4. Traverse the Dictionary
//iterate through a dictionary//Way One: fast traversal for(NSString *keyinchmd1) {Nsarray*values =[Md1 Objectforkey:key]; for(NSString *vinchvalues) {NSLog (@"%@", V); } } //mode two: normal traversalNsarray *allkey =[Md1 AllKeys]; for(intI=0; i<allkey.count;i++) {Nsarray*value =[md1 Objectforkey:allkey[i]]; }
This article introduces the Nsdirctionary class and the Nsmutabledirctionary class in OC.
Dark Horse programmer--foundation Framework of the--nsdirctionary class and its subclass Nsmutabledirctionary class