Chapter 11. Dictionaries and Sets

When you store data in an array, you can retrieve it by searching for that specific data or by keeping track of the index position of that data. Since searching for data or storing index positions of data can be cumbersome, there are two other data structures you can use called a dictionary and a set.

Dictionaries act like arrays, but they contain a paired key for each stored value, allowing you to search for a stored value just by knowing its key. Sets make it easy to compare lists and are useful for grouping items and determining whether one set is a subset or intersection of another set.

In this chapter, we explore the ins and outs of both of these data structures.

Dictionary Basics

A dictionary stores two chunks of data. First, there's the actual data or value itself that you want to store. Second, there's a key associated with that value. This key can be any short word or phrase that helps identify your actual data. Now instead of trying to search for your data, you just search for this key. Once you find the key, the key will point to your value, as shown in Figure 11-1.

A dictionary stores values and keys associated with that value.

Figure 11-1. A dictionary stores values and keys associated with that value.

For example, you could store a list of phone numbers in an array, but how would you know how to find the one phone number you wanted? Trying to remember which index position each phone number is stored in would prove difficult, and trying to search for a specific phone number is equally clumsy.

However, if you stored each phone number with a key, where each key contained a person's name, you could use the keys to find a desired phone number. Instead of searching for the phone number, you could search for the name John Doe or M. Smith, and that key would show you John Doe's or M. Smith's phone number.

To create a dictionary for storing data, you can create an NSDictionary or an NSMutableDictionary. The NSDictionary can store data but will not let you add, change, or remove data later. The NSMutableDictionary can store, add, change, or delete data from the dictionary while your program is running.

Creating and Putting Data in a Dictionary

When you create a dictionary, you have to decide whether you want to create a static dictionary (NSDictionary) that can only store data but not let you modify it or create a dynamic dictionary (NSMutableDictionary) that can store, add, or remove data while your program runs.

To create and initialize an NSDictionary, you need to use the dictionaryWithObjectsAndKeys method:

NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"Data1", @"Key1", @"Data2", @"Key2", nil];

When filling a dictionary with data using the dictionaryWithObjectsAndKeys method, you must make sure each chunk of data is immediately followed by its associated key. When you're done adding data, you must end the list with nil.

You can also use the dictionaryWithObjectsAndKeys method to create and initialize an NSMutableDictionary too. This can be convenient when storing one or two key-value pairs. However, if you need to store large amounts of data, you may find it easier to use the setObject and forKey methods to add a single key-value pair at a time.

To use the setObject and forKey methods, you must first declare an NSMutableDictionary with a pointer:

NSMutableDictionary *myOtherDictionary = [NSMutableDictionary dictionary];

This creates a pointer to an empty dictionary object. After you have created a dictionary, you can fill it with data. Data in a dictionary consists of a key-value pair where you store the data (value) along with its key.

For each chunk of data (a key-value pair) that you want to store in a dictionary, you have to use the setObject and forKey methods on a separate line like this:

[dictionaryName setObject: @"Data" forKey: @"Key"];

In the previous code, you would use the actual dictionary name and substitute your actual data and key in between the double quotation marks. If your dictionary was named phonebook and you wanted to store the data 555-1478 with a key John Doe, you could use the following:

[phoneBook setObject: @"555-1478" forKey: @"John Doe"];

Counting the Items Stored in a Dictionary

After you have stored data in a dictionary, you can always count the number of items stored in that dictionary by using the count command:

[dictionaryName count];

The dictionaryName simply represents the name of your dictionary, and the count command returns the number of items in that dictionary, so the entire line of previous code evaluates to a single number. If dictionaryName held six key-value pairs of data, the previous code would return the number 6.

To see how to count items in a dictionary, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
        [myDictionary setObject: @"555-1212" forKey: @"John Doe"];
        [myDictionary setObject: @"555-9999" forKey: @"Al Jones"];
        [myDictionary setObject: @"555-5555" forKey: @"Mary Smith"];
    
        int counter;
        counter = [myDictionary count];
        NSLog (@"Number of items = %i", counter);
    }
  4. Choose File

    Counting the Items Stored in a Dictionary
  5. Click the Build and Run button, or choose Build

    Counting the Items Stored in a Dictionary
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Counting the Items Stored in a Dictionary
  7. Choose Run

    Counting the Items Stored in a Dictionary
    2010-09-06 14:39:48.536 VariableTest[656:a0f] Number of items = 3

Retrieving an Item from a Dictionary

To retrieve an item from a dictionary, you only need to know the key associated with that data, using the objectForKey method like this:

[dictionaryName objectForKey: @"Key"];

The previous code returns the data associated with the key, so you may need to create a variable to hold this data:

NSString *myString;
myString = [myDictionary objectForKey: @"Key"];

To see how to retrieve data from a dictionary by using a key, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
        [myDictionary setObject: @"555-1212" forKey: @"John Doe"];
        [myDictionary setObject: @"555-9999" forKey: @"Al Jones"];
        [myDictionary setObject: @"555-5555" forKey: @"Mary Smith"];
    
        int counter;
        counter = [myDictionary count];
        NSLog (@"Number of items = %i", counter);
    
        NSString *myString;
        myString = [myDictionary objectForKey: @"Al Jones"];
        NSLog (@"Al Jones is associated with %@", myString);
    }
  4. Choose File

    Retrieving an Item from a Dictionary
  5. Click the Build and Run button, or choose Build

    Retrieving an Item from a Dictionary
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Retrieving an Item from a Dictionary
  7. Choose Run

    Retrieving an Item from a Dictionary
    2010-09-06 16:15:53.608 VariableTest[1041:a0f] Number of items = 3
    2010-09-06 16:15:53.611 VariableTest[1041:a0f] Al Jones is associated with 555-9999

Deleting Data from a Dictionary

If you have an NSMutableDictionary, you may want to remove data from it. To do this, you need to identify the key associated with that data and then use the removeObjectForKey method like this:

[dictionaryName removeObjectForKey: @"Key"];

In case you want to remove all data from a dictionary, you can use the removeAllObjects method:

[dictioinaryName removeAllObjects];

To see how the removeObjectForKey and removeAllObjects methods, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
       NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
        [myDictionary setObject: @"555-1212" forKey: @"John Doe"];
        [myDictionary setObject: @"555-9999" forKey: @"Al Jones"];
        [myDictionary setObject: @"555-5555" forKey: @"Mary Smith"];
    
        int counter;
        counter = [myDictionary count];
        NSLog (@"Number of items = %i", counter);
    
        NSString *myString;
        myString = [myDictionary objectForKey: @"Al Jones"];
        NSLog (@"Al Jones is associated with %@", myString);
    
        [myDictionary removeObjectForKey: @"John Doe"];
        NSLog (@"Number of items = %i", [myDictionary count]);
    
        [myDictionary removeAllObjects];
        NSLog (@"Number of items = %i", [myDictionary count]);
    }
  4. Choose File

    Deleting Data from a Dictionary
  5. Click the Build and Run button, or choose Build

    Deleting Data from a Dictionary
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Deleting Data from a Dictionary
  7. Choose Run

    Deleting Data from a Dictionary
    2010-09-06 16:46:21.010 VariableTest[1160:a0f] Number of items = 3
    2010-09-06 16:46:21.023 VariableTest[1160:a0f] Al Jones is associated with 555-9999
    2010-09-06 16:46:21.025 VariableTest[1160:a0f] Number of items = 2
    2010-09-06 16:46:21.025 VariableTest[1160:a0f] Number of items = 0

Copying a Dictionary

When you create an NSDictionary, you can add data to it only once. If you later want to add or delete data, you can't. The simplest solution is to create and use an NSMutableDictionary right from the start.

A second solution is to copy the contents of an NSDictionary into an NSMutableDictionary. Then you can manipulate the contents in the NSMutableDictionary. This might be handy when you want only one part of your program to modify the data in a dictionary but you don't want to risk giving your entire program the ability to modify the contents of a dictionary.

To copy the contents of a dictionary into another dictionary, you can use the addEntriesFromDictionary method like this:

[newDictionary addEntriesFromDictionary: oldDictionary];

This code copies the data from the oldDictionary and puts it into the newDictionary.

To see how the addEntriesFromDictionary method works, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSDictionary *staticDictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"Data1", @"Key1", @"Data2", @"Key2", nil];
        NSLog (@"Number of items in NSDictionary = %i", [staticDictionary count]);
    
        NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
        [newDict addEntriesFromDictionary: staticDictionary];
        NSLog (@"Count in new Dictionary = %i", [newDict count]);
    }
  4. Choose File

    Copying a Dictionary
  5. Click the Build and Run button, or choose Build

    Copying a Dictionary
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Copying a Dictionary
  7. Choose Run

    Copying a Dictionary
    2010-09-06 17:48:38.577 VariableTest[1374:a0f] Number of items in NSDictionary = 2
    2010-09-06 17:48:38.578 VariableTest[1374:a0f] Count  in new Dictionary = 2

Copying Dictionary Data Into an Array

After you've stored data in a dictionary, you'll essentially have two lists of data: the keys and the associated values. If you need to use this information separately, you can selectively copy all the keys or all the values from a dictionary and store them in an array. To retrieve all the keys or values stored in a dictionary, you need to use the allKeys or allValues method:

[dictionaryName allKeys];

or

[dictionaryName allValues];

Both the allKeys and allValues methods return an array, so you'll need to assign the previous code to an array:

NSArray *myArray = [myDictionary allKeys];

To see how to retrieve keys and values from a dictionary and store them in an array, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
        [myDictionary setObject: @"555-1212" forKey: @"John Doe"];
        [myDictionary setObject: @"555-5555" forKey: @"Mary Smith"];
        [myDictionary setObject: @"555-9999" forKey: @"Al Jones"];
        NSArray *myArray = [myDictionary allKeys];
        int i;
        for (i = 0; i < [myDictionary count]; i++)
        {
            NSLog (@"Key %i = %@", i, [myArray objectAtIndex:i]);
        }
    
        NSArray *secondArray = [myDictionary allValues];
        for (i = 0; i < [myDictionary count]; i++)
        {
            NSLog (@"Value %i = %@", i, [secondArray objectAtIndex:i]);
        }
    }
  4. Choose File

    Copying Dictionary Data Into an Array
  5. Click the Build and Run button, or choose Build

    Copying Dictionary Data Into an Array
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Copying Dictionary Data Into an Array
  7. Choose Run

    Copying Dictionary Data Into an Array
    2010-09-07 15:10:19.045 VariableTest[3579:a0f] Key 0 = John Doe
    2010-09-07 15:10:19.048 VariableTest[3579:a0f] Key 1 = Mary Smith
    2010-09-07 15:10:19.050 VariableTest[3579:a0f] Key 2 = Al Jones
    2010-09-07 15:10:19.058 VariableTest[3579:a0f] Value 0 = 555-1212
    2010-09-07 15:10:19.059 VariableTest[3579:a0f] Value 1 = 555-5555
    2010-09-07 15:10:19.060 VariableTest[3579:a0f] Value 2 = 555-9999

Sorting Keys

You can store data in a dictionary in any order. If you later need to sort this data, you can use the values stored in your dictionary to sort the keys by using the keysSortedByValueUsingSelector method. This method returns your sorted list of keys as an array.

To see how to sort a dictionary by its values, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
        [myDictionary setObject: @"75" forKey: @"John Doe"];
        [myDictionary setObject: @"42" forKey: @"Mary Smith"];
        [myDictionary setObject: @"09" forKey: @"Al Jones"];
    
        NSArray *sortedKeysArray = [myDictionary keysSortedByValueUsingSelector:@selector(compare:)];
        int i;
        for (i = 0; i < [sortedKeysArray count]; i++)
        {
            NSLog (@"Array element %i = %@", i, [sortedKeysArray objectAtIndex:i]);
        }
    }
  4. Choose File

    Sorting Keys
  5. Click the Build and Run button, or choose Build

    Sorting Keys
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Sorting Keys
  7. Choose Run

    Sorting Keys
    2010-09-07 16:19:47.672 VariableTest[3829:a0f] Array element 0 = Al Jones
    2010-09-07 16:19:47.677 VariableTest[3829:a0f] Array element 1 = Mary Smith
    2010-09-07 16:19:47.677 VariableTest[3829:a0f] Array element 2 = John Doe

Because the value 09 is associated with the key Al Jones, this value is the lowest so Al Jones gets stored first. The next highest value is 42, which means Mary Smith gets stored second. Finally, the highest value is 75, so John Doe gets stored last in the array.

Access All Items in a Dictionary

A dictionary can store dozens, hundreds, or thousands of key-value pairs of data. To access all items stored in a dictionary, you can use the for-in statement:

id myObject;
for (myObject in myDictionary)

The first line of this code declares an object variable using the id keyword. The second line of code tells the computer to access each key in the dictionary where each key gets stored in the myObject variable.

The for-in statement repeat for each key-value pair stored in the dictionary, so if you have 23 key-value pairs stored in a dictionary, the for-in loop will repeat 23 times.

To see how the for-in statement can access each item in a dictionary, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
        [myDictionary setObject: @"75" forKey: @"John Doe"];
        [myDictionary setObject: @"42" forKey: @"Mary Smith"];
        [myDictionary setObject: @"09" forKey: @"Al Jones"];
    
        id myObject;
        for (myObject in myDictionary)
        {
            NSLog (@"Key = %@", myObject);
            NSLog (@"Value = %@", [myDictionary objectForKey: myObject]);
            NSLog (@"*****");
        }
    }
  4. Choose File

    Access All Items in a Dictionary
  5. Click the Build and Run button, or choose Build

    Access All Items in a Dictionary
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Access All Items in a Dictionary
  7. Choose Run

    Access All Items in a Dictionary
    2010-09-07 17:27:37.196 VariableTest[4190:a0f] Key = John Doe
    2010-09-07 17:27:37.199 VariableTest[4190:a0f] Value = 75
    2010-09-07 17:27:37.199 VariableTest[4190:a0f] *****
    2010-09-07 17:27:37.200 VariableTest[4190:a0f] Key = Mary Smith
    2010-09-07 17:27:37.201 VariableTest[4190:a0f] Value = 42
    2010-09-07 17:27:37.202 VariableTest[4190:a0f] *****
    2010-09-07 17:27:37.202 VariableTest[4190:a0f] Key = Al Jones
    2010-09-07 17:27:37.202 VariableTest[4190:a0f] Value = 09
    2010-09-07 17:27:37.203 VariableTest[4190:a0f] *****

Using Sets

Besides arrays (see Chapter 8) and dictionaries, a third type of data structure available is a set. A set is a group of related data such as the numbers 5, 38, and 7, or the letters A, M, Y, and T. What makes sets useful, as data structures, are the three types of operations you can perform on a set: membership, union, and intersection.

The membership operation lets you quickly verify whether an item is a member of a set. This can be handy when you need to check whether something belongs in a larger group, such as a list of names that are allowed access to a computer. When a user types in a name, the computer could simply check whether this name is a member of the set of valid usernames.

If you stored a list of valid usernamesin an array or dictionary, you would have to exhaustively check each item in the array or dictionary with the user's name. If your array or dictionary contained 1,000 valid usernames, then you would have to compare the user's name with each of these 1,000 valid usernames before determining whether it matched. With a set, you could determine whether the name was a member of that valid username set in a single operation.

The union operation lets you combine two sets into a single set. The intersection operation lets you identify the common items shared by two sets.

Creating and Putting Data in a Set

You can create two types of sets: an NSSet, which can only store data but won't let you modify it, or an NSMutableSet, which lets you store, add, or remove data while your program runs.

Note

If you want to modify data in an NSSet, you can copy it into an NSMutableSet using the setWithSet method.

To create and initialize an NSSet or NSMutableSet, you need to create a pointer like this:

NSSet *mySet;
NSMutableSet *myOtherSet;

Then you can use the setWithObjects method to define a list of data to store in a set like this:

NSSet *mySet;
mySet = [NSSet setWithObjects: @"Joe", @"Mary", @"Sue", @"Olly", nil];

When using the setWithObjects method, make sure you end your list with nil, or else the computer won't know that it's reached the end of the data list that you want to add into the set.

If you have data already stored in an array, you can store this array data into a set by using the setWithArray method.

Counting the Number of Items in a Set

No matter how you fill a set, you can always count how many items are in that set by using the count method:

NSSet *mySet;
mySet = [NSSet setWithObjects: @"Joe", @"Mary", @"Sue", @"Olly", nil];
NSLog (@"Count = %i", [mySet count]);

This code would simply print the following:

Count = 4

Checking Whether Data Is in a Set

After you store data in a set, you can later check whether that set contains a specific chunk of data by using the containsObject method:

[setName containsObject: object];

This line of code returns a Boolean value of either YES (if the object is already in the set) or NO (if the object is not already stored in the set). To see how to use the containsObject method with a set, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSSet *mySet;
        mySet = [NSSet setWithObjects: @"Joe", @"Mary", @"Sue", @"Olly", nil];
        NSLog (@"Set members = %i", [mySet count]);
        if ([mySet containsObject:@"Joe"])
             {
                 NSLog (@"Found member in set");
             }
    else
             {
                 NSLog (@"No member found in set");
             }
    }
  4. Choose File

    Checking Whether Data Is in a Set
  5. Click the Build and Run button, or choose Build

    Checking Whether Data Is in a Set
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Checking Whether Data Is in a Set
  7. Choose Run

    Checking Whether Data Is in a Set
    2010-09-08 09:30:02.714 VariableTest[2090:a0f] Set members = 4
    2010-09-08 09:30:02.720 VariableTest[2090:a0f] Found member in set

Adding and Removing Data in a Set

If you create an NSMutableSet, you can add and remove data from that set while your program runs. To add an item to an NSMutableSet, you just need to use the addObject method and specify the item to add like this:

[mySet addObject: @"Bo"];

If you have data already stored in an array, you can add that entire array to a set using the addObjectsFromArray method like this:

NSArray *myArray = [NSArray arrayWithObjects: @"Hello",  @"world", @"Good-bye", nil];
[mySet addObjectsFromArray: myArray];

Just as you can add a single item or an group of items to a set, so can you also remove a single item or all items from a set. To remove an item from a set, you need to use the removeObject method and specify the exact item you want to remove from the set:

[mySet removeObject:@"Joe"];

If you just want to remove everything in a set, you can use the removeAllObjects method:

[mySet removeAllObjects];

To see how to add and remove items with sets, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSMutableSet *mySet;
    mySet = [NSMutableSet setWithObjects: @"Joe", @"Mary", @"Sue", @"Olly", nil];
        NSLog (@"Set members = %i", [mySet count]);
    
        [mySet addObject: @"Bo"];
        NSLog (@"Set members = %i", [mySet count]);
    
        NSString *object1 = @"Hello";
        NSString *object2 = @"world!";
        NSNumber *object3 = [NSNumber numberWithInt:45];
        NSArray *myArray = [NSArray arrayWithObjects: object1,  object2, object3, nil];
    
        [mySet addObjectsFromArray: myArray];
        NSLog (@"Set members = %i", [mySet count]);
    
        [mySet removeObject:@"Joe"];
        NSLog (@"Set members = %i", [mySet count]);
    
        [mySet removeAllObjects];
        NSLog (@"Set members = %i", [mySet count]);
    }
  4. Choose File

    Adding and Removing Data in a Set
  5. Click the Build and Run button, or choose Build

    Adding and Removing Data in a Set
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Adding and Removing Data in a Set
  7. Choose Run

    Adding and Removing Data in a Set
    2010-09-29 22:13:05.779 VariableTest[5949:a0f] Set members = 4
    2010-09-29 22:13:05.782 VariableTest[5949:a0f] Set members = 5
    2010-09-29 22:13:05.783 VariableTest[5949:a0f] Set members = 8
    2010-09-29 22:13:05.784 VariableTest[5949:a0f] Set members = 7
    2010-09-29 22:13:05.785 VariableTest[5949:a0f] Set members = 0

Accessing All Items in a Set

When you store data in a set, you may later want to know how to access each item. One way to do this is through a for-in statement:

id myObject;
for (myObject in mySet)

The first line of this code declares an object variable using the id keyword. The second line of code tells the computer to access each item in a set. If you have 30 chunks of data stored in a set, the for-in loop will repeat 30 times.

To see how the for-in statement can access each item in a set, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSSet *mySet;
        mySet = [NSSet setWithObjects: @"Joe", @"Mary", @"Sue", @"Olly", nil];
        NSLog (@"Set members = %i", [mySet count]);
    
        id testObject;
        for (testObject in mySet)
             {
                 NSLog (@"Member = %@", testObject);
             }
    }
  4. Choose File

    Accessing All Items in a Set
  5. Click the Build and Run button, or choose Build

    Accessing All Items in a Set
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Accessing All Items in a Set
  7. Choose Run

    Accessing All Items in a Set
    2010-09-08 09:58:36.571 VariableTest[2177:a0f] Set members = 4
    2010-09-08 09:58:36.577 VariableTest[2177:a0f] Member = Sue
    2010-09-08 09:58:36.578 VariableTest[2177:a0f] Member = Joe
    2010-09-08 09:58:36.582 VariableTest[2177:a0f] Member = Mary
    2010-09-08 09:58:36.583 VariableTest[2177:a0f] Member = Olly

Getting the Intersection of Two Sets

If you have two sets, you can check whether a common item appears in both sets by using the intersectsSet method like this:

[firstSet intersectsSet: secondSet]

If a common item appears in both sets, then the intersectsSet method returns a YES Boolean value. Otherwise, it returns a NO Boolean value.

Identifying a Subset of a Set

If all the members of one set are contained within another set, that first set is considered a subset. For example, suppose you defined a set like this:

mySet = [NSSet setWithObjects: @"Joe", @"Mary", @"Sue", @"Olly", nil];

If you defined another set like this:

otherSet = [NSSet setWithObjects: @"Joe", @"Mary", nil];

then the otherSet is considered to be a subset of mySet since every item in otherSet (Joe and Mary) is also contained in mySet. To identify a subset, you need to use the isSubsetOfSet method like this:

[otherSet isSubsetOfSet: mySet]

This code will return a YES Boolean value if otherSet is a subset of mySet. Otherwise, it returns a NO Boolean value. Note that if you reverse the position of the two sets, you can completely change the outcome:

[mySet isSubsetOfSet: otherSet]

In this case, the code asks whether mySet is a subset of otherSet. Since it is not, it returns a NO Boolean value.

To see how to check for the intersection and subset of a set, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored in the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSSet *mySet;
        mySet = [NSSet setWithObjects: @"Joe", @"Mary", @"Sue", @"Olly", nil];
        NSLog (@"Set members = %i", [mySet count]);
    
        NSSet *newSet;
        newSet = [NSSet setWithObjects: @"Bill", @"Mary", nil];
    
        if ([mySet intersectsSet: newSet])
        {
            NSLog (@"Found a match");
        }
        else
        {
            NSLog (@"No match");
        }
    
        NSSet *thirdSet;
        thirdSet = [NSSet setWithObjects: @"Joe", @"Mary", nil];
    
        if ([mySet isSubsetOfSet: newSet])
        {
            NSLog (@"Subset found");
        }
        else
        {
            NSLog (@"No subset");
        }
    
        if ([thirdSet isSubsetOfSet: mySet])
        {
            NSLog (@"Subset");
        }
    else
        {
            NSLog (@"No subset");
        }
    }
  4. Choose File

    Identifying a Subset of a Set
  5. Click the Build and Run button, or choose Build

    Identifying a Subset of a Set
  6. Quit the program, such as by clicking the Stop button or choosing Product

    Identifying a Subset of a Set
  7. Choose Run

    Identifying a Subset of a Set
    2010-09-29 22:37:32.985 VariableTest[6103:a0f] Set members = 4
    2010-09-29 22:37:32.988 VariableTest[6103:a0f] Found a match
    2010-09-29 22:37:32.989 VariableTest[6103:a0f] No subset
    2010-09-29 22:37:32.992 VariableTest[6103:a0f] Subset

Summary

Two other ways of storing data are dictionaries and sets. Dictionaries act like arrays that contain a paired key for each stored value, allowing you to search for a stored value just by knowing its key. Sets are useful for grouping items together and determining whether one set is a subset or intersection of another set. Sets make it easy to compare lists.

With both dictionaries and sets, you can add (and remove) one item at a time or add a bunch of data stored in an array. You can completely empty both a dictionary and a set.

Dictionaries and sets are advanced data structures that you may never need to use, but if you find yourself using arrays and finding that arrays are too clumsy, then consider using a dictionary or a set. By choosing the right data structure, you can save yourself time by not having to write a lot of code.

For example, if you stored data in two different arrays, trying to see whether one array contained all the elements of a second array would involve a lot of code to compare each item in the array. However, if you stored both arrays in two different sets, you could use the isSubsetOfSet method and determine whether one set is a subset of another using a single line of code.

Pick the right data structure, and your program can be easier to write and more reliable. Pick the wrong data structure, and your program could be harder to write and less reliable. The more you know about different types of data structures, the more likely you'll know how to choose the best one for your particular program.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.177.179