The dictionary in foundation is a data set composed of key-value pairs. For example, in Java, the key value must be unique in the dictionary object, in addition, the keys and values in the dictionary object cannot be nil ., If you want to indicate a null value in the dictionary object, you can use the nsnull object (here mainly refers to the value ). Dictionary objects can also be divided into unchangeable dictionary and variable dictionary.
1. Immutable dictionary
Nsnumber * num1 = [nsnumber numberwithint: 5]; nsnumber * num2 = [nsnumber numberwithint: 10]; nsnumber * num3 = [nsnumber numberwithint: 15]; // initialize a dictionary nsdictionary * dictionary = [nsdictionary dictionarywithobject: num1 forkey: @ "num"]; // obtain the value nsobject * object = [dictionary objectforkey: @ "num"]; nsdictionary * morenum = [nsdictionary dictionarywithobjectsandkeys: num1, @ "num1", num2, @ "num2", num2, @ "num3", nil]; // convert the key of the dictionary object into an enumeration object to traverse nsenumerator * enumerater = [morenum keyenumerator]; // obtain all keys nsarray * keyarray = [morenum allkeys]; // obtain all values nsarray * valuearray = [morenum allvalues]; // create a new dictionary that contains other dictionaries nsdictionary * newdic = [nsdictionary dictionarywithdictionary: dictionary]; // obtain the number of dictionaries nsinteger * thenum = [newdic count];
2. Variable dictionary nsmutabledictionary
It also inherits from nsdictionary, so all methods in nsdictionary apply
// Create a variable dictionary nsmutabledictionary * MDIC = [nsmutabledictionary dictionarywithobjectsandkeys: num1, @ "num1", num2, @ "num2", num2, @ "num3", nil]; // Add the entire dictionary to the variable dictionary object. nsdictionary * dic2 = [nsdictionary dictionarywithobject: @ "nihao" forkey: @ "hello"]; [MDIC addentriesfromdictionary: dic2]; // append a key-value pair to the variable dictionary [MDIC setvalue: @ "jimgreen" forkey: @ "name"]; // traverses the object, retrieve Data for (ID key in MDIC) {id obj = [MDIC objectforkey: Key]; nslog (@ "% @", OBJ );}