Creating Property Lists

The examples in this section demonstrate how to create and work with property lists. The error checking code has been removed for clarity. In practice, it is vital that you check for errors because passing bad parameters into Core Foundation routines can cause your application to crash.

Listing 1 shows you how to create a very simple property list—an array of CFString objects.

Listing 1  Creating a simple property list from an array

#include <CoreFoundation/CoreFoundation.h>
#define kNumNames 6
 
void main () {
 
    CFStringRef names[kNumNames];
    names[0] = CFSTR("Steve");
    names[1] = CFSTR("Susan");
    names[2] = CFSTR("Sally");
    names[3] = CFSTR("Patrick");
    names[4] = CFSTR("Jeff");
    names[5] = CFSTR("Jane");
 
    // Create a property list using the string array of names
    CFArrayRef array = CFArrayCreate(kCFAllocatorDefault, (const void **)names,
                kNumNames, &kCFTypeArrayCallBacks);
 
    // Convert the plist into XML data
    CFErrorRef myError;
    CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, array, kCFPropertyListXMLFormat_v1_0, 0, &myError);
 
    // Check for errors, do things with the data
 
    // Clean up CF objects.
    CFRelease(array);
    CFRelease(xmlData);
    CFRelease(myError);
}

Listing 2 shows how the contents of xmlData, created in Listing 1, would look if printed to the screen.

Listing 2  XML created by the sample program

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <string>Steve</string>
    <string>Susan</string>
    <string>Sally</string>
    <string>Patrick</string>
    <string>Jeff</string>
    <string>Jane</string>
</array>
</plist>