Property Lists Programming Guide
Property Lists Programming Guide
Programming Guide
Contents
2
Contents
NSData 40
NSArray 41
NSDictionary 41
3
Tables and Listings
4
Introduction to Property Lists
Property lists organize data into named values and lists of values using several object types. These types give
you the means to produce data that is meaningfully structured, transportable, storable, and accessible, but
still as efficient as possible. Property lists are frequently used by applications running on both OS X and iOS.
The property-list programming interfaces for Cocoa and Core Foundation allow you to convert hierarchically
structured combinations of these basic types of objects to and from standard XML. You can save the XML data
to disk and later use it to reconstruct the original objects.
This document describes property lists and their various representations, and how to work with them using
both certain Foundation classes of Cocoa and Property List Services of Core Foundation.
Note: The user defaults system, which you programmatically access through the NSUserDefaults
class, uses property lists to store objects representing user preferences. This limitation would seem
to exclude many kinds of objects, such as NSColor and NSFont objects, from the user default
system. But if objects conform to the NSCoding protocol they can be archived to NSData objects,
which are property list–compatible objects. For information on how to do this, see ““Storing NSColor
in User Defaults”“; although this article focuses on NSColor objects, the procedure can be applied
to any object that can be archived.
5
Introduction to Property Lists
Organization of This Document
● “Reading and Writing Property-List Data” (page 36) describes how to save property lists to files or URL
resources and how to restore them later.
● “Old-Style ASCII Property Lists” (page 40) is an appendix that describes the format of old-style (OpenStep)
ASCII property lists.
6
Quick Start for Property Lists
This mini-tutorial gives you a quick, practical introduction to property lists. You start by specifying a short
property list in XML. Then you design an application that, when it launches, reads and converts the elements
of the XML property list into their object equivalents and stores these objects in instance variables. The
application displays these object values in the user interface and allows you to change them. When you quit
the application, it writes out the modified property list as XML. When you relaunch the application, the new
values are displayed.
Double-click the Data.plist file in Xcode (you’ll find it in the Resources folder). Xcode displays an empty
property list in a special editor. Edit the property list so that it looks like the following example:
You can also edit the property list in a text editor such as TextEdit or BBEdit. When you’re finished, it should
look like the following XML code.
7
Quick Start for Property Lists
Define Storage for the Property-List Objects
<string>408-974-0000</string>
<string>503-333-5555</string>
</array>
</dict>
</plist>
Because the property-list file is in the Resources folder, it will be written to the application’s main bundle when
you build the project.
In Xcode, select the Classes folder and choose New File from the File menu. Select the Objective-C Class template
and name the files “Controller.h” and “Controller.m”. Make the following declarations in Controller.h.
#import <Cocoa/Cocoa.h>
NSString *personName;
NSMutableArray *phoneNumbers;
@end
In Controller.m, have the compiler synthesize accessor methods for these properties:
@implementation Controller
@synthesize personName;
@synthesize phoneNumbers;
8
Quick Start for Property Lists
Create the User Interface
@end
Note: This mini-tutorial shows user-interface techniques and programming interfaces that are
specific to OS X. If you want to use an iOS application for this example, you must use techniques
and API that are appropriate to that platform. The code specific to property lists is applicable to both
platforms.
For reasons of simplicity and efficiency, you’ll next bind the text field to the personName property. But your
Controller object will act as a data source for the table. Let’s start with the text field.
1. Drag an generic Object proxy from the Library into the nib document window. Select it and, in the Identify
pane of the inspector, type or select “Controller” for its class identity.
2. Drag an Object Controller object from the Library into the nib document window. Control-drag (or
right-click-drag) a line from Object Controller to Controller and, in the connection window that pops up,
select “content”.
9
Quick Start for Property Lists
Create the User Interface
3. Select the editable text field and, in the Bindings pane of the inspector, bind the value attribute of the
text field according to the following:
● Bind to: Object Controller
● Controller Key: selection
● Model Key Path: personName
Next, Control-drag a line from File’s Owner in the nib document window (File’s Owner in this case represents
the global NSApplication object) to the Controller object and then select delegate in the connection
window. As you’ll see, the application delegate (Controller) plays a role in saving the property list to its XML
representation.
For the table view, Control-drag a line from the table view to the Controller object in the nib document window.
Select the dataSource outlet in the connection window. Save the nib file. Copy the code in Listing 1-1 to
Controller.m.
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return self.phoneNumbers.count;
- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row {
withObjects:[NSArray arrayWithObject:object]];
Note that the last method synchronizes changes to items in the table view with the phoneNumbers mutable
array that backs it.
10
Quick Start for Property Lists
Read in the Property List
- (id) init {
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!temp) {
11
Quick Start for Property Lists
Write Out the Property List
return self;
This code first gets the file-system path to the file containing the XML property list (Data.plist) in the
~/Documents directory. If there is no file by that name at that location, it obtains the property-list file from
the application’s main bundle. Then it uses the NSFileManager method contentsAtPath: to read the
property list into memory as an NSData object. After that, it calls the NSPropertyListSerialization class
method propertyListFromData:mutabilityOption:format:errorDescription: to convert the
static property list into the corresponding property-list objects—specifically, a dictionary containing a string
and an array of strings. It assigns the string and the array of strings to the appropriate properties of the Controller
object.
Listing 1-3 Converting and writing the property list to the application bundle
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
NSString *error;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(plistData) {
12
Quick Start for Property Lists
Run and Test the Application
else {
NSLog(error);
[error release];
return NSTerminateNow;
This code creates an NSDictionary object containing the values of the personName and phoneNumbers
properties and associates these with the keys “Name” and “Phones”. Then, using the
dataFromPropertyList:format:errorDescription: class method of NSPropertyListSerialization,
it converts this top-level dictionary and the other property-list objects it contains into XML data. Finally, it
writes the XML data to Data.plist in the user’s Documents directory.
13
About Property Lists
A property list is a structured data representation used by Cocoa and Core Foundation as a convenient way
to store, organize, and access standard types of data. It is colloquially referred to as a “plist.” Property lists are
used extensively by applications and other software on OS X and iOS. For example, the OS X Finder—through
bundles—uses property lists to store file and directory attributes. Applications on iOS use property lists in their
Settings bundle to define the list of options displayed to users. This section explains what property lists are
and when you should use them.
Note: Although user and application preferences use property lists to structure and store data, you
should not use the property list API of either Cocoa or Core Foundation to read and modify them.
Instead, use the programming interfaces provided specifically for this purpose—see Preferences and
Settings Programming Guide and Preferences Programming Topics for Core Foundation for more
information.
From the basic abstraction derives both a static representation of the property-list data and a runtime
representation of the property list. The static representation of a property list, which is used for storage, can
be either XML or binary data. (The binary version is a more compact form of the XML property list.) In XML,
each type is represented by a certain element. The runtime representation of a property list is based on objects
corresponding to the abstract types. The objects can be Cocoa or Core Foundation objects. Table 2-1 lists the
types and their corresponding static and runtime representations.
14
About Property Lists
What is a Property List?
By convention, each Cocoa and Core Foundation object listed in Table 2-1 is called a property-list object.
Conceptually, you can think of “property list” as being an abstract superclass of all these classes. If you receive
a property list object from some method or function, you know that it must be an instance of one of these
types, but a priori you may not know which type. If a property-list object is a container (that is, an array or
dictionary), all objects contained within it must also be property-list objects. If an array or dictionary contains
objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the
various property-list methods and functions. And although NSDictionary and CFDictionary objects allow
their keys to be objects of any type, if the keys are not string objects, the collections are not property-list
objects.
Because all these types can be automatically cast to and from their corresponding Cocoa types, you can use
the Core Foundation property list API with Cocoa objects. In most cases, however, methods provided by the
NSPropertyListSerialization class should provide enough flexibility.
15
About Property Lists
When to Use Property Lists
In some situations, the property-list architecture may prove insufficient. If you need a way to store large,
complex graphs of objects, objects not supported by the property-list architecture, or objects whose mutability
settings must be retained, use archiving. See Archives and Serializations Programming Guide for more
information.
If you are looking for a way to implement user or application preferences, Cocoa provides a class specifically
for this purpose. While the user defaults system does use property lists to store information, you do not have
to access these plists directly. See Preferences and Settings Programming Guide and Preferences Programming
Topics for Core Foundation for more information.
Note that property lists should be used for data that consists primarily of strings and numbers. They are very
inefficient when used with large blocks of binary data.
XML property lists are more portable than the binary alternative and can be manually edited, but binary property
lists are much more compact; as a result, they require less memory and can be read and written much faster
than XML property lists. In general, if your property list is relatively small, the benefits of XML property lists
outweigh the I/O speed and compactness that comes with binary property lists. If you have a large data set,
binary property lists, keyed archives, or custom data formats are a better solution.
16
Creating Property Lists Programmatically
You can create a graph of property-list objects by nesting property-list objects of various types in arrays and
dictionaries. The following sections give details on doing this programmatically.
NSDictionary *innerDict;
NSString *name;
NSDate *dob;
NSArray *scores;
[NSNumber numberWithFloat:4.9],
17
Creating Property Lists Programmatically
Creating a Property List in Objective-C
format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
Note: The NSPropertyListSerialization class method shown in this example serializes the
property-list objects into an XML property list. It is described more fully in “Serializing a Property List
” (page 26).
The XML output of the code in Listing 3-1 is shown in Listing 3-2.
<plist version="1.0">
<dict>
<key>Lincoln</key>
<dict>
<key>DOB</key>
<date>1809-02-12T09:18:00Z</date>
<key>Name</key>
<string>Abraham Lincoln</string>
<key>Scores</key>
<array>
<integer>8</integer>
<real>4.9000000953674316</real>
<integer>9</integer>
18
Creating Property Lists Programmatically
Creating a Property List in Core Foundation
</array>
</dict>
<key>Washington</key>
<dict>
<key>DOB</key>
<date>1732-02-17T01:32:00Z</date>
<key>Name</key>
<string>George Washington</string>
<key>Scores</key>
<array>
<integer>6</integer>
<real>4.5999999046325684</real>
<integer>6</integer>
</array>
</dict>
</dict>
</plist>
Listing 3-3 shows you how to create a very simple property list—an array of CFString objects.
#include <CoreFoundation/CoreFoundation.h>
#define kNumFamilyMembers 5
void main () {
CFStringRef names[kNumFamilyMembers];
CFArrayRef array;
CFDataRef xmlData;
19
Creating Property Lists Programmatically
Creating a Property List in Core Foundation
names[0] = CFSTR("Marge");
names[1] = CFSTR("Homer");
names[2] = CFSTR("Bart");
names[3] = CFSTR("Lisa");
names[4] = CFSTR("Maggie");
&kCFTypeArrayCallBacks );
// Clean up CF types.
CFRelease( array );
CFRelease( xmlData );
Listing 3-4 shows how the contents of xmlData, created in Listing 3-3, would look if printed to the screen.
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>Marge</string>
<string>Homer</string>
20
Creating Property Lists Programmatically
Creating a Property List in Core Foundation
<string>Bart</string>
<string>Lisa</string>
<string>Maggie</string>
</array>
</plist>
A CFNumber object serves simply as a wrapper for C numeric values. Core Foundation includes functions to
create a CFNumber, obtain its value, and compare two CFNumber objects. Note that CFNumber objects are
immutable with respect to value, but type information may not be maintained. You can get information about
a CFNumber object’s type, but this is the type the CFNumber object used to store your value and may not be
the same type as the original C data.
When comparing CFNumber objects, conversion and comparison follow human expectations and not C
promotion and comparison rules. Negative zero compares less than positive zero. Positive infinity compares
greater than everything except itself, to which it compares equal. Negative infinity compares less than everything
except itself, to which it compares equal. Unlike standard practice, if both numbers are NaNs, then they compare
equal; if only one of the numbers is a NaN, then the NaN compares greater than the other number if it is
negative, and smaller than the other number if it is positive.
Listing 3-5 shows how to create a CFNumber object from a 16-bit integer and then get information about the
CFNumber object.
CFNumberRef aCFNumber;
CFNumberType type;
Int32 size;
Boolean status;
aCFNumber = CFNumberCreate(kCFAllocatorDefault,
21
Creating Property Lists Programmatically
Creating a Property List in Core Foundation
kCFNumberSInt16Type,
&sint16val);
type = CFNumberGetType(aCFNumber);
size = CFNumberGetByteSize(aCFNumber);
kCFNumberSInt16Type,
&sint16val);
Listing 3-6 creates another CFNumber object and compares it with the one created in Listing 3-5.
CFNumberRef anotherCFNumber;
CFComparisonResult result;
sint16val = 382;
anotherCFNumber = CFNumberCreate(kCFAllocatorDefault,
kCFNumberSInt16Type,
&sint16val);
switch (result) {
case kCFCompareLessThan:
break;
case kCFCompareEqualTo:
22
Creating Property Lists Programmatically
Creating a Property List in Core Foundation
break;
case kCFCompareGreaterThan:
break;
23
Understanding XML Property Lists
The preferred way to store property lists on OS X and iOS is as an XML file called an XML property list or XML
plist. These files have the advantages of being human-readable and in the standards-based XML format. The
NSArray and NSDictionary classes both have methods for saving themselves as XML plists (for example,
descriptionWithLocale: and writeToFile:atomically:), and also have methods to convert XML
property lists back to objects in memory. CFPropertyList provides functions for converting property lists to
and from their XML representation.
Core Foundation supports XML as the exclusive medium for the static representation of property lists on disk.
Cocoa allows property lists to be stored on disk as XML property lists, in binary form, and as “old-style” property
lists. The old-style property lists can only be read, not written; see “Old-Style ASCII Property Lists” (page 40)
for further information.
Generally, there is little need to create or edit XML property yourself, but if you do, use Xcode’s built-in property
list editor or the Property List Editor application (which is part of the tools package). You should not edit the
XML data in a text editor unless you are very familiar with XML syntax and the format of property lists. Moreover,
the elements in an XML property list could change in future releases, so keep that in mind.
Even if you don’t edit XML property lists, it is useful to understand their structure for design and debugging
purposes. Like every XML file, XML plists begin with standard header information, and contain one root object,
wrapped with the <plist> document type tag. The <plist> object also contains exactly one object, denoted
by one of the XML elements listed in Table 2-1 (page 15).
Graphs of objects are created by nesting the XML elements listed in Table 2-1. When encoding dictionaries,
the element <key> is used for dictionary keys, and one of the other property list tags is used for the key’s
value. Here is an example of XML data generated from a property list:
<plist version="1.0">
<dict>
<key>Author</key>
<string>William Shakespeare</string>
<key>Lines</key>
<array>
24
Understanding XML Property Lists
</array>
<key>Birthdate</key>
<integer>1564</integer>
</dict>
</plist>
Note that data bytes are base-64 encoded between the <data> and </data> tags.
25
Serializing a Property List
Using the NSPropertyListSerialization class or Property List Services (Core Foundation), you can serialize
property lists in their runtime (object) form to a static representation that can be stored in the file system; later
you can deserialize that static representation back into the original property-list objects. Property-list serialization
automatically takes account of endianness on different processor architectures—for example, you can correctly
read on an Intel-based Macintosh a binary property list created on a PowerPC-based Macintosh.
The property-list serialization APIs allow you to save graphs of property-list objects as binary data as well as
XML property lists. See “Property List Representations” (page 16) for the relative advantages and disadvantages
of XML and binary property lists.
Listing 5-1 saves an object graph of property-list objects as an XML property list in the application bundle.
NSData *xmlData;
NSString *error;
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(xmlData) {
26
Serializing a Property List
Saving and Restoring a Property List in Objective-C
else {
NSLog(error);
[error release];
Note: To avoid a memory leak, it is necessary to release the error-description string returned via
indirection in the third parameter of dataFromPropertyList:format:errorDescription:
(as shown in Listing 5-1). This is a rare exception to the standard memory-management rules.
Because you cannot save a property list in the old-style (OpenStep) format, the only valid format parameters
for this method are NSPropertyListXMLFormat_v1_0 and NSPropertyListBinaryFormat_v1_0. The
NSData object returned by dataFromPropertyList:format:errorDescription: encapsulates the XML
or binary data. You can then call the writeToFile:atomically: or writeToURL:atomically: method
to store the data in the file system.
Note: If the root property-list object is an NSDictionary or NSArray object (the typical case), you
can serialize the property list as an XML property list and write it out to disk at the same time using
the appropriate methods of those classes. See “Reading and Writing Property-List Data” (page 36)
for details.
To restore a property list from a data object by deserializing it, call the
propertyListFromData:mutabilityOption:format:errorDescription: class method of the
NSPropertyListSerialization class, passing in the data object. Listing 5-2 creates an immutable property
list from the file at path:
NSString *error;
NSPropertyListFormat format;
id plist;
27
Serializing a Property List
Saving and Restoring a Property List in Core Foundation
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&error];
if(!plist){
NSLog(error);
[error release];
The mutability-option parameter of the deserialization method controls whether the deserialized property-list
objects are created as mutable or immutable. You can specify that all objects are immutable, that only the
container objects are mutable, or that all objects are mutable. Unless you have a specific reason to mutate the
collections and other objects in a deserialized property list, use the immutable option. It is faster and uses less
memory.
If the method call returns nil, the final parameter—the error-description string—states the reason the
deserialization did not succeed.
Note: In OS X v10.5 (and earlier versions of the operating system), it is necessary to release the
error-description string in Listing 5-2.
Listing 5-3 shows you how to create a complex property list, convert it to XML, write it to disk, and then re-create
the original data structure using the saved XML. For more information about using CFDictionary objects see
Collections Programming Topics for Core Foundation .
28
Serializing a Property List
Saving and Restoring a Property List in Core Foundation
Listing 5-3 Saving and restoring property list data (Core Foundation)
#include <CoreFoundation/CoreFoundation.h>
#define kNumKids 2
#define kNumBytesInPic 10
CFURLRef fileURL );
int main () {
CFPropertyListRef propertyList;
CFURLRef fileURL;
propertyList = CreateMyDictionary();
false ); // is it a directory?
CFRelease(propertyList);
CFRelease(propertyList);
CFRelease(fileURL);
29
Serializing a Property List
Saving and Restoring a Property List in Core Foundation
return 0;
CFMutableDictionaryRef dict;
CFNumberRef num;
CFArrayRef array;
CFDataRef data;
int yearOfBirth;
CFStringRef kidsNames[kNumKids];
kidsNames[0] = CFSTR("John");
kidsNames[1] = CFSTR("Kyra");
yearOfBirth = 1965;
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks );
// Because the values are retained as they are placed into the
30
Serializing a Property List
Saving and Restoring a Property List in Core Foundation
CFDictionarySetValue( dict,
CFSTR("City of Birth"),
CFSTR("Springfield") );
kCFNumberIntType,
&yearOfBirth );
CFRelease( num );
kNumKids,
&kCFTypeArrayCallBacks );
CFRelease( array );
NULL,
0,
&kCFTypeArrayCallBacks );
CFRelease( array );
CFRelease( data );
return dict;
CFURLRef fileURL ) {
CFDataRef xmlData;
Boolean status;
31
Serializing a Property List
Saving and Restoring a Property List in Core Foundation
SInt32 errorCode;
status = CFURLWriteDataAndPropertiesToResource (
NULL,
&errorCode);
CFRelease(xmlData);
CFPropertyListRef propertyList;
CFStringRef errorString;
CFDataRef resourceData;
Boolean status;
SInt32 errorCode;
kCFAllocatorDefault,
fileURL,
NULL,
NULL,
&errorCode);
resourceData,
32
Serializing a Property List
Saving and Restoring a Property List in Core Foundation
kCFPropertyListImmutable,
&errorString);
if (resourceData) {
CFRelease( resourceData );
} else {
CFRelease( errorString );
return propertyList;
Listing 5-4 shows how the contents of xmlData, created in Listing 5-1 (page 26), would look if printed to the
screen.
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Year Of Birth</key>
<integer>1965</integer>
<key>Pets Names</key>
<array/>
<key>Picture</key>
<data>
PEKBpYGlmYFCPA==
</data>
<key>City of Birth</key>
<string>Springfield</string>
<key>Name</key>
33
Serializing a Property List
Using Property List Services with Cocoa
<string>John Doe</string>
<key>Kids Names</key>
<array>
<string>John</string>
<string>Kyra</string>
</array>
</dict>
</plist>
To create an XML property list from a property list object, call the CFPropertyListCreateXMLData function.
This code fragment saves the property list plist into a file at path:
NSData *xmlData;
(CFPropertyListRef)plist);
[xmlData release];
To restore a property list object from XML data, call the CFPropertyListCreateFromXMLData function.
This code fragment restores property list from the XML plist file at path with mutable containers but immutable
leaves:
34
Serializing a Property List
Using Property List Services with Cocoa
NSString *errorString;
NSData *xmlData;
id plist;
plist = (id)CFPropertyListCreateFromXMLData(kCFAllocatorDefault,
(CFDataRef)xmlData, kCFPropertyListMutableContainers,
(CFStringRef *)&errorString);
35
Reading and Writing Property-List Data
Note: To function properly, these methods require that all objects contained by the
NSDictionary or NSArray root object be property-list objects.
● You can serialize the property-list objects to an NSData object using the
dataFromPropertyList:format:errorDescription: class method and then save that object by
calling the writeToFile:atomically: or writeToURL:atomically: methods of the NSData class.
To read the property-list data back into your program, first initialize an allocated NSData object by invoking
initWithContentsOfFile: or initWithContentsOfURL: or call a corresponding class factory method
such as dataWithContentsOfFile:. Then call the
propertyListFromData:mutabilityOption:format:errorDescription: class method of
NSPropertyListSerialization, passing in the data object.
Note: The code examples in “Read in the Property List” (page 11) and “Write Out the Property
List” (page 12) of “Quick Start for Property Lists” illustrate the second approach.
The first approach is simpler—it requires only one method invocation instead of two—but the second approach
has its advantages. It allows you to convert the runtime property list to binary format as well as an XML property
list. When you convert a static representation of a property list back into a graph of objects, it also lets you
specify with more flexibility whether those objects are mutable or immutable.
36
Reading and Writing Property-List Data
Using Objective-C Methods to Read and Write Property-List Data
To expand on this last point, consider this example. You have an XML property list whose root object is an
NSArray object containing a number of NSDictionary objects. If you load that property list with this call:
a is an immutable array with immutable dictionaries in each element. Each key and each value in each dictionary
are also immutable.
ma is a mutable array with immutable dictionaries in each element. Each key and each value in each dictionary
are immutable.
If you need finer-grained control over the mutability of the objects in a property list, use the
propertyListFromData:mutabilityOption:format:errorDescription: class method, whose second
parameter permits you to specify the mutability of objects at various levels of the aggregate property list. You
could specify that all objects are immutable (NSPropertyListImmutable), that only the container (array
and dictionary) objects are mutable (NSPropertyListMutableContainers), or that all objects are mutable
(NSPropertyListMutableContainersAndLeaves).
propertyListFromData:plistData
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&error];
This call produces a mutable array with mutable dictionaries in each element. Each key and each value in each
dictionary are themselves also mutable.
37
Reading and Writing Property-List Data
Using Core Foundation Functions to Read and Write Property-List Data
Listing 6-1 includes a fragment of the larger code example in “Saving and Restoring a Property List in Core
Foundation” (page 28) that illustrates the use of these functions.
Listing 6-1 Writing and reading property lists using Core Foundation functions
CFURLRef fileURL ) {
CFDataRef xmlData;
Boolean status;
SInt32 errorCode;
status = CFURLWriteDataAndPropertiesToResource (
&errorCode);
CFRelease(xmlData);
CFPropertyListRef propertyList;
CFStringRef errorString;
CFDataRef resourceData;
38
Reading and Writing Property-List Data
Using Core Foundation Functions to Read and Write Property-List Data
Boolean status;
SInt32 errorCode;
status = CFURLCreateDataAndPropertiesFromResource(
kCFAllocatorDefault,
fileURL,
NULL,
NULL,
&errorCode);
resourceData,
kCFPropertyListImmutable,
&errorString);
if (resourceData) {
CFRelease( resourceData );
else {
CFRelease( errorString );
return propertyList;
}
You may also write and read property lists to the file system using the functions
CFPropertyListWriteToStream and CFPropertyListCreateFromStream. These functions require that
you open and configure the read and write streams yourself.
39
Old-Style ASCII Property Lists
The OpenStep frameworks, which Cocoa is derived from, used an ASCII format for storing property lists. These
files store information equivalent to the information in XML property lists, and are still supported by Cocoa,
but for reading only. Old-style plist support remains primarily for legacy reasons. You read old-style property
lists by calling the propertyListFromData:mutabilityOption:format:errorDescription: method
of NSPropertyListSerialization.
ASCII property lists support the four primary property list data types: NSString, NSData, NSArray, and
NSDictionary. The following sections describe the ASCII syntax for each of these types.
Important: Cocoa allows you to read old-style ASCII property lists only. You may not write them.
NSString
A string is enclosed in double quotation marks, for example:
"This is a string"
The quotation marks can be omitted if the string is composed strictly of alphanumeric characters and contains
no white space (numbers are handled as strings in property lists). Though the property list format uses ASCII
for strings, note that Cocoa uses Unicode. Since string encodings vary from region to region, this representation
makes the format fragile. You may see strings containing unreadable sequences of ASCII characters; these are
used to represent Unicode characters.
NSData
Binary data is enclosed in angle brackets and encoded in hexadecimal ASCII. Spaces are ignored. For example:
<0fbd777 1c2735ae>
40
Old-Style ASCII Property Lists
NSArray
NSArray
An array is enclosed in parentheses, with the elements separated by commas. For example:
The items don’t all have to be of the same type (for example, all strings)—but they normally are. Arrays can
contain strings, binary data, other arrays, or dictionaries.
NSDictionary
A dictionary is enclosed in curly braces, and contains a list of keys with their values. Each key-value pair ends
with a semicolon. For example:
Note the omission of quotation marks for single-word alphanumeric strings. Values don’t all have to be the
same type, because their types are usually defined by whatever program uses them. Dictionaries can contain
strings, binary data, arrays, and other dictionaries.
Below is a sample of a more complex property list. The property list itself is a dictionary with keys “AnimalSmells,”
“AnimalSounds,” and so on; each value is also a dictionary, with key-value pairs.
41
Document Revision History
Date Notes
2009-07-30 Added links to inline Cocoa concepts and made minor modifications.
2008-11-19 Combined Cocoa and Core Foundation documents on property lists and
reorganized material. Added a "Quick Start" mini-tutorial and a chapter
on programmatically creating property lists. Mentioned iOS as a platform
on which property lists are important.
2003-06-30 Corrected error in restore property list sample code in “Using Old-Style
Property Lists” and “Using XML Property Lists”.
2003-05-02 “Serialized” property lists renamed “Binary” to better reflect their purpose.
2003-04-21 Corrected error in restore property list sample code in “Binary Property
Lists”.
2003-03-21 Enumerated NSArray and NSDictionary methods available for writing XML
plists in “XML Property Lists”. Added link to Core Foundation Property List
documentation, and removed references to Property List “Services”.
42
Document Revision History
Date Notes
2002-11-12 Revision history was added to existing topic. It will be used to record
changes to the content of the topic.
43
Apple Inc.
Copyright © 2010 Apple Inc.
All rights reserved.