Searching Collections

Beta documentation : This document has not received a full technical review and therefore might contain inaccuracies.

Collection Services includes several programming interfaces for finding values (and, in the case of CFDictionary, keys) in collection objects. The CF Type GetValueIfPresent 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 8 illustrates how the CFDictionaryContainsKey function might be used.

Listing 8 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 it the collection, the function tells you where it should go; the CFArrayBSearchValues function thus helps you to sort values in mutable CFArray objects in place. Listing 9 shows how this function might be called.

Listing 9 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 Base Services CFComparatorFunction prototype. 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 Using Tree Structures for more information.


© 1999 Apple Computer, Inc. – (Last Updated 07 September 99)