Basic usage of nsdictionary and nsmutabledictionary
1. Immutable Dictionary Nsdictionary
Dictionary initialization
NSNumber *numobj = [NSNumber numberwithint:100];
Class with an element.
Nsdictionary *dic = [nsdictionary dictionarywithobject:numobj forkey:@ "key"];
Initialize two elements
Nsdictionary *dic = [nsdictionary dictionarywithobjectsandkeys:numobj, @ "Valuekey", NumObj2, @ "value2", nil];
Initializes a new dictionary with a new dictionary containing otherdic
Nsdictionary *dic = [Nsdictionary dictionarywithdictionary:otherdic];
Initializing a dictionary with the contents of a file
Nsdictionary *dic = [Nsdictionary Dictionarywithcontentsoffile:path];
Common methods
Get Dictionary number
Nsinteger count = [dic count];
Get the corresponding value object by key
NSObject *valueobj = [dic objectforkey:@ "key"];
Converts the dictionary key to an enumeration object that iterates through the
Nsenumerator *enumerator = [dic keyenumerator];
Gets the collection of all keys
Nsarray *keys = [dic AllKeys];
Get a collection of all values
Nsarray *values = [dic allvalues];
2. Variable array nsmutabledictionary
Initialize an empty mutable dictionary
Nsmutabledictionary *dic2 = [nsmutabledictionary dictionarywithobjectsandkeys:@ "v1", @ "Key1", @ "V2", @ "Key2", nil];
Nsdictionary *dic3 = [nsdictionary dictionarywithobject:@ "v3" forkey:@ "Key3"];
To add an entire Dictionary object to a dictionary 2 object 3
[Dic2 ADDENTRIESFROMDICTIONARY:DIC3];
One of the best new Key3 and Value3 to the Dictionary 2 object
[Dic2 setvalue:@ "Value3" forkey:@ "Key3"];
Initialize an empty mutable dictionary
Nsmutabledictionary *dic1 = [Nsmutabledictionary dictionary];
The empty Dictionary 1 object content setting is the same as the Dictionary 2 object
[Dic1 Setdictionary:dic2];
Delete the corresponding value of key1 in the dictionary
[DIC1 [email protected] "Key1"];
Nsarray *array = [Nsarray arraywithobjects:@ "Key1", nil];
Removes the contents of the dictionary 1 based on the specified array (key)
[Dic2 Removeobjectsforkeys:array];
Remove all objects from a dictionary
[Dic1 removeallobjects];
Traverse Dictionary
Quick Enumeration
For (ID key in dic) {
ID obj = [dic objectforkey:key];
NSLog (@ "%@", obj);
}
General enumeration
Nsarray *keys = [dic AllKeys];
INR length = [keys count];
for (int i = 0; i < length;i++) {
ID key = [keys objectatindex:i];
ID obj = [dic objectforkey:key];
NSLog (@ "%@", obj);
}
Enumeration by enumeration type
Nsenumerator *enumerator = [dic keyenumerator];
ID key = [enumerator nextobject];
while (key) {
ID obj = [dic objectforkey:key];
NSLog (@ "%@", obj);
key = [Enumerator nextobject];
}
IOS Intro-nsdictionary and Nsmutabledictionary