The Ownership Policy in Action--Some Examples

Users of Core Foundation objects--both in code that receives Core Foundation objects and in code that returns or passes such objects--should observe the Core Foundation ownership policy. Consistent application of the policy wherever Core Foundation objects are received, passed, or returned is highly recommended because it is sure to save you a lot of headaches, particularly in the form of runtime errors and memory leaks.

The following fragments of code illustrate three common situations: a Set accessor function, a Get accessor function, and a function that holds onto a Core Foundation object until a certain condition is met. First the Set function:

static CFStringRef title = NULL:
void SetTitle(CFStringRef newTitle) {
	CFStringRef temp = title;
	title = CFStringCreateCopy(newTitle);
	CFRelease(temp);
}

The above example uses a static CFStringRef variable to hold the retained CFString object. You could use other means for storing it but you must put it, of course, in some place that isn't local to the receiving function. The function assigns the current title to a local variable before it retains the new title and releases the old title. It releases after retaining in case the CFString object passed in is the same object as the one currently held.

Notice that in the above example the object is copied and not retained. The reason for this is that a reference to a mutable CFString might be passed in--even though the parameter is typed as CFStringRef . Therefore you copy the object so that it won't be changed while you hold it. However, if you know that a received object will not be changed while you hold it, you can and should retain it. You should copy an object if the object is or could be mutable and you need your own unique version of it.

The corresponding Get function is much simpler:

CFStringRef GetTitle() {
	return title;
}

By simply returning an object you are returning a weak reference to it. In other words, the pointer value is copied to the receiver's variable but the retention count is unchanged. The same thing happens when an element from a collection is returned.

The following function retains an object retrieved from a collection until it no longer needs it, then releases it. The object is assumed to be immutable.

static CFStringRef title = NULL:
void MyFunction(CFDictionary dict, Boolean aFlag) {
	if (!title && !aFlag) {
		title = (CFStringRef)CFDictionaryGetValue(dict, CFSTR("title"));
		title = CFRetain(title);
	}
	/* Do something with title here. */
	if (aFlag) {
		CFRelease(title);
	}
}

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