// Create an unchangeable dictionary nsdictionary * dictionary; dictionary = [nsdictionary dictionarywithobjectsandkeys: @ "Good lucky", @ "why", @ "Bye bye", @ "how ", nil]; // The number of elements in it is an odd number (excluding the last nil, because it is the number of // output dictionaries corresponding to a group of ID keys nslog (@ "Number of dictionaries = % lu", [dictionary count]); /* obtain all the key values in the dictionary. nsenumerator is used to traverse the object of each index in the Set * // obtain all the key values in objectenumerator and obtain the key in the object keyenumerator. value: nsenumerator * enumerator = [dictionary keyenumer Ator]; // replace keyenumerator with objectenumerator to get the value (1) // define an object ID object of an uncertain type; // traverse the output while (Object = [enumerator nextobject]) {nslog (@ "key value: % @", object); // here we get the key value, you can obtain it through (1, you can also obtain the value corresponding to the key value obtained here. // you can obtain the value through the objectforkey method of the nsdictionary object. // actually, the object that defines objectvalue can be directly used with nsobject, because we already know its type, Id uses ID objectvalue = [dictionary objectforkey: object]; If (objectvalue! = Nil) {nslog (@ "% @ corresponding value is % @", object, objectvalue );}} // create a changeable dictionary. It is dynamic. // We Need to initialize a space. Use dictionarywithcapacity nsmutabledictionary * mutabledictionary = [nsmutabledictionary dictionarywithcapacity: 5]. // here, the space size is 5. When the added data exceeds the limit, the space size will automatically expand. // Add data. Note: the ID key is paired with [mutabledictionary setobject: @ "Good lucky" forkey: @ "why"]; [mutabledictionary setobject: @ "Bye bye" forkey: @ "how"]; // method for obtaining the key value and value without traversing the output, allkeys and allvalues nslog (@ "output all key values =%@", [mutabledictionary allkeys]); nslog (@ "output all values =%@", [mutabledictionary allvalues]); // dynamically reflected in the ability to dynamically add data. Now, the key value is changed to the value of why, // The value is changed after printing, but nsdictionary cannot modify [mutabledictionary setobject: @ "good" forkey: @ "why"]; nslog (@ "output all key values =%@", [mutabledictionary allkeys]); nslog (@ "output all values =%@", [mutabledictionary allvalues]); // dynamically Delete // delete data with the specified key value [mutabledictionary removeobjectforkey:...]; // delete all data [mutabledictionary removeallobjects];
Source: http://blog.csdn.net/like7xiaoben/article/details/7526730