Core Animation properties and Reference Counting

Q: After reading up on properties in Objective-C I've noticed that a number of properties declared by Core Animation use the default "assign" semantic. However, when I set the property using a Core Foundation object the object is still retained. Why?

A: By default if a property declaration does not specify "assign", "retain" or "copy", then the declaration is assumed to use assign semantics, which means the assigned value is referenced without being retained. Declarations using retain and copy only work when the property's data type specifies an Objective-C object, as otherwise the compiler flags an error for the declaration. For example:

Listing 1: Retained property with Core Foundation data type

@property(retain) CGColorRef myProperty;

"error: property 'myProperty' with 'retain' attribute must be of object type"

Core Animation makes use of a number of data types provided by Core Graphics that are derived Core Foundation data types such as CGColorRef and CGPathRef. Since the error above would be flagged if these properties were declared with retain or copy semantics, Core Animation declarations do not specify either.

To ensure expected behavior, Core Animation implements retain or copy semantics where appropriate for all data types that it exposes. To avoid memory leaks when using these properties, you must release the objects after they are assigned. An example of properly assigning a CALayer's background color property is below:

Listing 2: Properly assigning a background color.

CGColorRef color = CGColorCreateGenericRGB(1.0, 0.5, 0.25, 1.0);
layer.backgroundColor = color;

For more information on properties see The Objective-C 2.0 Programming Language.

For a guide to using Core Animation, see the Core Animation Programming Guide.

Document Revision History

Date Notes
2008-11-24 First Version

Posted: 2008-11-24

Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.