Objective-C: 08-NSDictionary and NSSet, nssetnsdictionary

Source: Internet
Author: User
Tags allkeys

Objective-C: 08-NSDictionary and NSSet, nssetnsdictionary
NSDictionary and NSMutableDictionaryNSSet and NSMutableSte

Dictionary

Dictionary: it can be divided into variable dictionary NSDictionary and variable dictionary NSMutableDictionary. The data in the dictionary is saved in the form of a key-value pair. The key and value can be any object. Generally, strings are used as keys.

Using Dictionaries can greatly improve the programming efficiency. Let's look at an example of expressing music information using dictionaries. the structure of music information is basically the same, but some music may be different. For example, some music may be prepared by many people, and some music may have reference information.

In figure (a), the part enclosed by each box is a dictionary object. The complete information of a piece of music is composed of multiple dictionary objects. For example, you can obtain the name of a song, use lyrics to obtain the author, and use music to obtain the author. use note to get the remarks. of course, one of them may be empty.

In this example, keys and values are all string objects. When values are composed of multiple strings, they can be enclosed, in this case, the value of the dictionary object is equivalent to an array object. in addition to strings, Dictionary object values also support any object. for example, you can also define the sound or video of a song as a dictionary object.

Let's take a look at an example that uses a dictionary object to represent a university classroom. (B) as an example of music, the section surrounded by each box is a dictionary object. the keyword capacity is used to indicate how many mic and screen files can be installed in the classroom to indicate whether the classroom is equipped with a microphone and a projection screen. the value of the numeric type can be either a string or NSNumber.

In a process-oriented language, subscript or member name is generally used to obtain the value of an array or struct. The keys and values of dictionary objects can be object types. Therefore, they are highly scalable and can be used in various environments.

The dictionary key must be unique. In addition, nil cannot be used as the dictionary key.

The value of a dictionary object can be any object except nil, array object, or dictionary object.

NSDictionary

NSDictionary dictionary inherited from NSObject is an immutable dictionary. All elements stored in the dictionary exist in the form of key-value pairs (key-value), and the data is stored according to key1: value1 key2: value2... storage. the key value must be unique and the value can be repeated. the dictionary can only store data of the object type. The key value and value must be objects, and the key-value pairs stored in the dictionary are unordered.

 

  Create

1. Create an empty dictionary init constructor dictionary

NSDictionary *dic = [[NSDictionary alloc] init];NSDictionary *dic1 = [NSDictionary dictionary];

2. Create the dictionary initWithObjectsAndKeys with key-value pairs:

Convenient constructor method dictionaryWithObjectsAndKeys:

NSDictionary *dic2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"18", @"age", @"zhangSan", @"name", @"yao", @"gender", nil];NSLog(@"%@", dic2);

Print:

13:01:40. 306 Myself [1711: 145326] {

Age = 18;

Gender = yao;

Name = zhangSan;

}

 

  Note:

1. When the value is in the front, the key value is in the back

2. The dictionary is unordered.

3. The dictionary ends with nil at creation.

4. The key value is generally a String object, and the value can be arbitrary, but must also be of the object type.

 

3. Use an existing dictionary object to initialize another dictionary, initWithDictionary:

   Convenient constructor method dictionaryWithDictionary:

NSDictionary *dic3 = [[NSDictionary alloc] initWithDictionary:dic2];

4. Access


1.Obtain the number of key-value pairs in the dictionary. countNSInteger dCount = dic3.count;

2.Obtain all key values in the dictionary. allKeysNSArray * keyArray = dic3.allKeys; 3.Obtain all value in the dictionary. allValuesNSArray * valueArray = dic3.allValues; 4.Return the corresponding value objectForKey Based on the given key value:NSString * value = [dic3 objectForKey: @ "age"]; NSLog (@ "% @", value); // print 18

5. traverse the dictionary

When forin traverses the dictionary, the key value of the dictionary is traversed by default.

for (NSString *key in dic3) {    NSString *value = [dic3 objectForKey:key];    NSLog(@"%@ = %@", key, value);}

 

Print:

13:13:57. 952 Myself [1737: 151680] age = 18

13:13:57. 952 Myself [1737: 151680] name = zhangSan

13:13:57. 952 Myself [1737: 151680] gender = yao

 

 

NSMutableDictionary

NSMutableDictionary: a variable dictionary inherited from NSDictionary. It manages variable key-value pairs. Compared with NSDictionary, NSDictionary adds a method for deleting, adding, and modifying the elements in the dictionary, NSMutableDictionary automatically manages the memory.

  Create

  Create and initialize a variable dictionary named "capacity ".

  Convenient constructor method dictionaryWithCapacity

NSMutableDictionary *mDic = [[NSMutableDictionary alloc] initWithCapacity:0];NSMutableDictionary *mDic1 = [NSMutableDictionary dictionaryWithCapacity:0];   

  Add and delete

  1. Add a key-Value Pair setObject:<# (Id) #>ForKey:<# (Id <NSCopying>) #>

[mDic setObject:@"wangMaZi" forKey:@"L"];[mDic setObject:@"zhangSan" forKey:@"B"];

  2. Modify the key-Value Pair setObject:<# (Id) #>ForKey:<# (Id <NSCopying>) #>

[mDic setObject:@"xiaoPing" forKey:@"B"];NSLog(@"%@", mDic);

Note: The method for adding and modifying a key-value pair is the same. If no corresponding key value exists in the dictionary, add it. If the dictionary contains the same key value, this overwrites the data because the key value in the dictionary is unique.

 

  3. Delete the removeObjectForKey pair based on the key value:

[mDic removeObjectForKey:@"L"];

  4. Delete all key-value pairs in the dictionaryRemoveAllObjects

 

[mDic removeAllObjects];

 

 

NSSet

The Foundation framework provides NSSet, which is a set of Single-value objects. Unlike NSArray, NSSet stores unordered objects, and only one object can be saved.

  Collection features:

    1. All elements in the set are unique.

2. Elements in the set are unordered.

3. Only elements of the object type in the collection

  

  1. Create an empty set init constructor method set

NSSet *set = [[NSSet alloc] init];NSSet *set1 = [NSSet set];

  2. Create a set of initWithObjects with elements:

Convenient constructor method setWithObjects:

 NSSet *set2 = [[NSSet alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", nil];

  3. Use an array to initialize the set object arrayWithObjects:

If the array contains repeated elements, you can remove the repeated elements from the array. Only one element is saved in the set.

NSArray *sArr = [NSArray arrayWithObjects:@"1", @"2", @"2", @"4", @"5", nil];NSSet *set3 = [NSSet setWithArray:sArr];NSLog(@"%@", set3);

14:37:46. 206 Myself [1784: 178830] {(

1,

4,

2,

5

)}

 Access

4.Returns the number of elements in a collection.NSInteger * sCount = set2.count; 5.Obtains the random element anyObject in a collection.NSString * sValue = set2.anyObject; 6.Obtain all the elements in the Set allObjectsNSArray * sArray = set2.allObjects;

 Judgment

 7. Determine whether the collection contains an object containsObject:

BOOL isCountain = [set2 containsObject: @ "1"]; NSLog (@ "% @", isCountain? @ "Include": @ "does not contain"); // contains

 8. Determine if it is a subset of isSubsetOfSet:

NSSet * set4 = [NSSet setWithObjects: @ "1", @ "2", @ "3", nil]; NSSet * set5 = [NSSet setWithObjects: @ "1 ", @ "2", nil]; BOOL isSub = [set5 isSubsetOfSet: set4]; NSLog (@ "% @", isSub? @ "Is a subset": @ "not a subset"); // It is a subset.

  9. Determine whether two sets have intersection intersectsSet:

BOOL isInter = [set4 intersectsSet: set5]; NSLog (@ "% @", isInter? @ "Intersection": @ "no intersection"); // Intersection

10. Determine whether two sets are the same as isw.toset:

BOOL isSame = [set4 isEqualToSet: set5]; NSLog (@ "% @", isSame? @ "Same": @ "different ");

 

NSMutableSet

NSMutableSet variable set, inherited from NSSet

  1. Create setWithCapacity:

NSMutableSet *mSet = [NSMutableSet setWithCapacity:0];[mSet addObject:@"1"];[mSet addObject:@"123"];[mSet addObject:@"456"];NSLog(@"%@", mSet);

  2. Delete the removeObject element in the variable set:

[mSet removeObject:@"1"];NSLog(@"%@", mSet);

  3. removeAllObjects

[mSet removeAllObjects];NSLog(@"%@", mSet);

 

Summary:

1. Ordered angle: arrays ordered, dictionaries and sets are disordered.

2. can I access it through Subscript: array is acceptable, dictionary and set are not allowed

3. Whether the elements can be repeated: the array can be repeated, the key value in the dictionary cannot be repeated, the value can be repeated, and the elements in the set cannot be repeated.

4. Printed style: array: () dictionary: {} set :{()}

 

Note: arrays and dictionaries are often used in combination;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.