The Collection Services types CFArray, CFDictionary, CFSet, and CFBag offer similar sets of functions for manipulating the values contained by mutable collections: adding values, removing values, replacing values, and so on. There are some differences in behavior based on whether the collection ensures the uniqueness of keys and values. Table 2 summaries the behavior of the mutability functions. The Operation column identifies the type of operation using the substring found in a mutability function, such as
CFDictionaryReplaceValue
.
With fixed-size mutable collections, you must take care to avoid adding beyond the capacity limit. A fixed-size collection will let you add as many values as you want, but gives no notice when you exceed the capacity. However, doing so will result in undefined behavior that is most likely undesirable.
The CFArray type features one mutability operation that is special to it. With the
CFArraySortValues
function you can sort the values contained by the array. A comparator function, which must conform to the Base Services
CFComparatorFunction
type, is used to compare values. Listing 11 gives an example of the use of the
CFArraySortValues
function.
Listing 11 Sorting an array
CFMutableArrayRef createSortedArray(CFArrayRef anArray) { CFIndex count = CFArrayGetCount(anArray); CFMutableArrayRef marray = CFArrayCreateMutableCopy(NULL, count, anArray); CFArraySortValues(marray, CFRangeMake(0, count), (CFComparatorFunction)CFStringCompare, NULL); return marray; }
Notice that the
CFStringCompare
function is used, in this case, to compare CFString objects. Core Foundation provides other comparator functions that are of the
CFComparatorFunction
type, notably
CFDateCompare
and
CFNumberCompare
. When an array holds Core Foundation objects, you can pass in an appropriate predefined comparator function to the
CFArraySortValues
function to sort those objects.