Nsdictionary serves the same purpose as the dictionary in Java and provides a set of "healthy-value" pairs.
For example, the dictionary is used to store employee numbers into employee names. The number is a key (unique) and the name is a value.
Nsdictionary example:
// Use dictionarywithobjectsandkeys to initialize a static dictionary. Remember to end nsdictionary * employes = [nsdictionary dictionarywithobjectsandkeys: @ "Zhang San", @ "1", @ "Li Si ", @ "2", @ "", @ "3", nil]; nsstring * firstemployes = [employes objectforkey: @ "1"];
Nsmutabledictionary example:
// Use dictionary to initialize a dynamic dictionary nsmutabledictionary * employes = [nsmutabledictionary dictionary]; [employes setobject: @ "James" forkey: @ "1"]; // Add a key-value [employes setobject: @ "" forkey: @ "2"]; // Add a key-value [employes setobject: @ "" forkey: @ "3"]; // Add a key-value // output nslog (@ "No: 1, % @", [employes objectforkey: @ "1"]); nslog (@ "No: 2, % @", [employes objectforkey: @ "2"]); nslog (@ "No: 3, % @", [employes objectforkey: @ "3"]);
Program output]
1. Zhang San 2, Li Si 3, Wang Wu
Common nsdictionary methods:
+ (ID) dictionarywithobjectsandkeys: obj1, obj2,... nil // Add objects and key values in sequence to create a dictionary. -(ID) initwithobjectsandkeys: obj1, key1, obj2, key2 ,... nil // initialize a new dictionary and add objects and values in sequence-(unsigned INT) Count // return the number of records in the dictionary-(nsenumerator *) keyenumerator // return all keys in the dictionary to an nsenumerator object-(nsarray *) keyssortedbyvalueusingselector :( SEL) selector // sort the rows with the method specified by selector-(nsenumerator *) objectenumerator // return the value in the dictionary to an nsenumerator type object-(ID) objectforkey: Key // return the value of the specified key
Common nsmutabledictionary methods:
+ (ID) dictionarywithcapacity: Size // create a variable Dictionary of size-(ID) initwithcapacity: Size // initialize a variable Dictionary of size-(void) removeallobjects // delete all elements in the dictionary-(void) removeobjectforkey: Key // Delete the element of the dictionary Key location-(void) setobject: OBJ forkey: Key // Add (OBJ, key) to the dictionary. If the key already exists, replace the value with obj.