Searching Collections

Core Foundation includes several programming interfaces for finding values (and, in the case of CFDictionary, keys) in collection objects. The CFTypeGetValueIfPresent functions, described in Getting the Values of Collections, report on the existence of values in dictionaries, sets, and bags. You can also use functions with “Contains” in their names to determine whether a collection holds a value or key. Listing 1 illustrates how the CFDictionaryContainsKey function might be used.

Listing 1  Searching a CFDictionary object for a key

if (CFDictionaryContainsKey(mappingTable, (const void*)lowerCharsetName)) {
    result = (CFStringEncoding)CFDictionaryGetValue(mappingTable, (const void*)lowerCharsetName);
}

For CFArray objects, the CFArrayBSearchValues function offers a more sophisticated search option. This function searches for a specified value in a sorted array using a binary search algorithm. If the value doesn’t exist in the collection, the function tells you where it should go; the CFArrayBSearchValues function thus helps you to keep a sorted mutable array sorted. Listing 2 shows how this function might be called.

Listing 2  Searching for a value in a CFArray object

CFIndex position = CFArrayBSearchValues(aMutArray, CFRangeMake(0,CFArrayGetCount(anArray)), (const void *)CFSTR("String Three"), CFStringCompare, 0);

The fourth parameter of the CFArrayBSearchValues function must be a pointer to a function that conforms to the CFComparatorFunction type. This comparator function is supposed to know how to compare values in the array. In the given example CFStringCompare is used because it conforms to CFComparatorFunction and it knows how to compare CFString values. There are other predefined Core Foundation comparator functions that you can use, such as CFNumberCompare and CFDateCompare.

Upon return of the above call, the function’s CFIndex result can indicate one of the following:

You can use the CFArrayContainsValue to determine whether the result is the first of the listed alternatives.

The CFTree type defines a different group of functions for locating contained values (that is, subtrees). See Creating and Copying Collections for more information.