Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

4.4 Collections

A big part of any language's standard library is providing collections, and Foundation is no exception. It includes a small number of primitive collection types defined as opaque C types and then uses these to build more complex Objective-C types.

In contrast with the C++ standard template library, Cocoa collections are heterogeneous and can contain any kind of object. All objects are referenced by pointer, so the amount of space needed to store pointers to any two objects is always the same: one word.

4.4.1 Comparisons and Ordering

For ordered collections, objects implement their own comparison. While almost any object can be stored in an array, there are more strict requirements for those that are to be stored in a set (which doesn't allow duplicates) or used as keys in a dictionary. Objects that are stored in this way must implement two methods: -hash and -isEqual:. These have a complex relationship.

  1. Any two objects that are equal must return YES to isEqual: when compared in either order.
  2. Any two objects that are equal must return the same value in response to -hash.
  3. The hash of any object must remain constant while it is stored in a collection.

The first of these is somewhat difficult to implement by itself. It means that the following must always be true:

[a isEqual: b] == [b isEqual: a]

If this is ever not true, then some very strange and unexpected behavior may occur. This may seem very easy to get right, but what happens when you compare an object to its subclass or to an object of a different class? Some classes may allow comparisons with other classes; for example, an object encapsulating a number may decide it is equal to another object if they both return the same result to intValue.

An example of when this can cause problems is in the use of objects as keys in dictionaries. When you set a value for a given key in a dictionary, the dictionary first checks if the key is already in the dictionary. If it is, then it replaces the value for that key. If not, then it inserts a new value.

If [a isEqual: b] returns YES but [b isEqual: a] returns NO, then you will get two different dictionaries depending on whether you set a value for the key a first and then the value for the key b. In general, therefore, it is good practice to only use one kind of object as keys in any given collection (most commonly NSStrings).

Listing 4.6 gives a simple example of this. This defines three new classes. The first, A, is a simple superclass for both of the others, which returns a constant value for the hash. It implements copyWithZone: in a simple way. Since this object is immutable (it has no instance variables, therefore no state, therefore no mutable state), instead of copying we just return the original object with its reference count incremented. This is required since the dictionary will attempt to copy keys, to ensure that they are not modified outside the collection (more on this later).

Listing 4.6. An invalid implementation of isEqual: [from: examples/isEqualFailure/dict.m]

 1| #import <Foundation/Foundation.h>
 3| @interface A : NSObject {}
 4| @end
 5| @interface B : A {}
 6| @end
 7| @interface C : A {}
 8| @end
 9| @implementation A
10| - (id) copyWithZone: (NSZone*)aZone { return [self retain]; }
11| - (NSString*)description { return [self className]; }
12| - (NSUInteger)hash { return 0; }
13| @end
14| @implementation B
15| - (BOOL) isEqual: (id)other { return YES; }
16| @end
17| @implementation C
18| - (BOOL) isEqual: (id)other { return NO; }
19| @end
21| int main(void)
22| {
23|     id pool = [NSAutoreleasePool new];
24|     NSObject *anObject = [NSObject new];
25|     NSMutableDictionary *d1 = [NSMutableDictionary new];
26|     [d1 setObject: anObject forKey: [B new]];
27|     [d1 setObject: anObject forKey: [C new]];
28|     NSMutableDictionary *d2 = [NSMutableDictionary new];
29|     [d2 setObject: anObject forKey: [C new]];
30|     [d2 setObject: anObject forKey: [B new]];
31|     NSLog(@"d1:_%@", d1);
32|     NSLog(@"d2:_%@", d2);
33|     return 0;
34| }

The two subclasses, B and C, have similarly trivial implementations of the -isEqual: method. One always returns YES; the other returns NO. In the main() function, we create two mutable dictionaries and set two objects for them, one with an instance of A and one with an instance of B as keys.

When we run the program, we get the following result:

$ gcc -framework Foundation dict.m &&./a.out
2009-01-07 16:54:15.735 a.out[28893:10b] d1: {
    B = <NSObject: 0x1003270>;
2009-01-07 16:54:15.737 a.out[28893:10b] d2: {
    B = <NSObject: 0x1003270>;
    C = <NSObject: 0x1003270>;

The first dictionary only contains one object, the second one contains two. This is a problem. In a more complex program, the keys may come from some external source. You could spend a long time wondering why in some instances you got a duplicate key and in others you got different ones.

Equality on objects of different classes makes the hash value even more tricky, since both objects must have the same hash value if they are equal. This means that both classes must use the same hash function, and if one has some state not present in the other, then this cannot be used in calculating the hash. Alternatively, both can return the same, constant, value for all objects. This is simple, but if taken to its logical conclusion means all objects must return 0 for their hash, which is far from ideal.

The third requirement is the hardest of all to satisfy in theory, but the easiest in practice. An object has no way of knowing when it is in a collection. If you use an object as a key in a dictionary, or insert it into a set, then modify it, then its hash might change. If its hash doesn't change, then it might now be breaking the second condition.

In practice, you can avoid this by simply avoiding modifying objects while they are in collections.

4.4.2 Primitive Collections

As mentioned earlier, Foundation provides some primitive collections as C opaque types. As of 10.5, these gained an isa pointer and so can be used both via their C and Objective-C interfaces. The biggest advantage of this is that they can be stored in other collections without wrapping them in NSValue instances. Most of the time, if you use these, you will want to use them via their C interfaces. These are faster and provide access to more functionality. The object interfaces are largely to support collections containing weak references in a garbage-collected environment. If you are not using garbage collection, or wish to use the primitive collections to store other types of value, then the C interfaces are more useful.

The simplest type of collection defined in Foundation, beyond the primitive C types like arrays and structures, is NSHashTable. This is a simple hash table implementation. It stores a set of unique values identified by pointers. A hash table is created using a NSHashTableCallBacks structure, which defines five functions used for interacting with the objects in the collection:

  • hash defines a function returning hash value for a given pointer.
  • isEqual provides the comparison function, used for testing whether two pointers point to equal values.
  • retain is called on every pointer as it is inserted into the hash table.
  • release is the inverse operation, called on objects that are removed.
  • describe returns an NSString describing the object, largely for debugging purposes.

All of these correspond to methods declared by NSObject, and you can store these in a hash table by using the predefined set of callbacks called NSObjectHashCallBacks or NSNonRetainedObjectHashCallBacks, depending on whether you want the hash table to retain the objects when they are inserted.

The hash table model is extended slightly by NSMapTable. An NSMapTable is effectively a hash table storing pairs and only using the first element for comparisons. These are defined by two sets of callbacks, one for the key and one for the value.

Unlike other Cocoa collections, both of these can be used to store non-object types, including integers that fit in a pointer, or pointers to C structures or arrays.

4.4.3 Arrays

Objective-C, as a pure superset of C, has access to standard C arrays, but since these are just pointers to a blob of memory they are not very friendly to use. OpenStep defined two kinds of arrays: mutable and immutable. The NSArray class implements the immutable kind and its subclass NSMutableArray implements the mutable version.

Unlike C arrays, these can only store Objective-C objects. If you need an array of other objects, you can either use a C array directly or create a new Objective-C class that contains an array of the required type.

NSArray is another example of a class cluster. The two primitive methods in this case are -count and -objectAtIndex:. These have almost identical behavior to their counterparts in NSString, although the latter returns objects instead of unicode characters.

As with strings, immutable arrays can be more efficient in terms of storage than their C counterparts. When you create an array from a range in another array, for example, you may get an object back that only stores a pointer to the original array and the range—a view on the original array—avoiding the need to copy large numbers of elements.

Since Cocoa arrays are objects, they can do a lot of things that plain data arrays in C can't. The best example of this is the -makeObjectsPerformSelector: method, which sends a selector to every single element in an array. You can use this to write some very concise code.

With 10.5, Apple added NSPointerArray. This can store arbitrary pointers (but not non-pointer types). Unlike NSArray, it can store NULL values and in the presence of garbage collection can be configured to use weak references. In this case, a NULL value will be used for any object that is destroyed while in the array.

The Cocoa arrays are very flexible. They can be used as both stacks and queues without modification since they allow insertion at both ends with a single method. Using an array as a stack is very efficient. A stack is defined by three operations: push, pop, and top. The first of these adds a new object to the top of the stack. NSMutableArray's -addObject: method does this. The pop operation removes the last object to have been pushed onto the stack, which is exactly what -removeLastObject does. The remaining operation, top, gets the object currently on the top of the stack (at the end of the array) and is provided by NSArray's -lastObject method.

Using an array as a queue is less efficient. A queue has objects inserted at one end and removed from the other. You can cheaply insert objects at the end of the array, but inserting them at the front is very expensive. Similarly, you can remove the object from the end of an array very efficiently, but removing the first one is more expensive. The removeObjectAtIndex: method may not actually move the objects in the array up one if you delete the first element, however. Since NSMutableArray is a class cluster, certain implementations may be more efficient for removing the first element, but there is no way to guarantee this.

4.4.4 Dictionaries

Dictionaries, sometimes called associative arrays are implemented by the NSDictionary class. A dictionary is a mapping from objects to other objects, a more friendly version of NSMapTable that only works for objects.

It is common to use strings as keys in dictionaries, since they meet all of the requirements for a key. In a lot of Cocoa, keys for use in dictionaries are defined as constant strings. Somewhere in a header file you will find something like:

extern NSString *kAKeyForSomeProperty;

Then in a private implementation file somewhere it will say

NSString *kAKeyForSomeProperty = @"kAKeyForSomeProperty";

This pattern is found all over Cocoa and in various third-party frameworks. Often you can just use the literal value, rather than the key, but this will use a bit more space in the binary and be slightly slower, so there isn't any advantage in doing so.

As you might expect, the mutable version of a dictionary is an NSMutableDictionary, which adds -setObject:forKey: and -removeObjectForKey: primitive methods, and a few convenience methods.

Dictionaries can often be used as a substitute for creating a new class. If all you need is something storing some structured data, and not any methods on this data, then dictionaries are quite cheap and are very quick to create. You can create a dictionary in a single call, like this:

[NSDictionary dictionaryWithObjectsAndKeys:
    image, @"image",
    string, @"caption", nil];

This is a variadic constructor that takes a nil-terminated list of objects as arguments and inserts each pair into the dictionary as object and key. You can then access these by sending a -objectForKey: message to the resulting dictionary.

Cocoa uses this in quite a few places. Notifications store a dictionary, with a specific set of keys defined for certain notification types. This makes it easy to add additional data in the future.

4.4.5 Sets

Just as NSDictionary is an object built on top of the primitive NSMapTable, NSSet is an object built on top of the primitive NSHashTable. As in mathematics, sets in Cocoa are unordered collections of unique objects. Unlike an array, an object can only be in a set once.

The rules for determining whether two objects are equal are very simple. Objects in a set are first split into buckets using their hash, or some bits of the their hash for small sets. When a new object is inserted, the set first finds the correct bucket for its hash. It then tests it with every object in that bucket using -isEqual:. If none of them match it, then the new object is inserted.

For a NSSet, this is only done when the set is initialized from an array or a list of objects as arguments. NSMutableSet allows objects to be added to an existing set and will perform this check every time. As you might imagine, this is very slow (O(n)) if all of the objects have the same hash value.

In addition to basic sets, OpenStep provided NSCountedSet. This is a subclass of NSMutableSet and so is also mutable. Unlike normal sets, counted sets (also known as bags) allow objects to exist more than once in the collection. Like sets, they are unordered. Another way of thinking of them is unordered arrays, although an array allows distinct-but-equal objects to exist in the same collection, while a counted set just keeps a count of objects.

With 10.3, NSIndexSet was also added. This is a set of integers that can be used as indexes in an array or some other integer-indexed data structure. Internally, NSIndexSet stores a set of non-overlapping ranges, so if you are storing sets containing contiguous ranges, then it can be very efficient.

NSIndexSet is not very useful by itself. It is made useful by NSArray methods such as -objectsAtIndexes:, which returns an array containing just the specified elements. Since the indexes are all within a certain range, operations on an NSArray using an index set only require bounds checking once, rather than for every lookup, which can make things faster.

  • + Share This
  • 🔖 Save To Your Account