Object C

Page 70

CHAPTER 5

Declared Properties

Property Declaration A property declaration begins with the keyword @property. @property can appear anywhere in the method declaration list found in the @interface block of a class. @property can also appear in the declaration of a protocol or category. @property(attributes) type name;

The @property directive declares a property. An optional parenthesized set of attributes provides additional details about the storage semantics and other behaviors of the property—see “Property Declaration Attributes” (page 70) for possible values. Like any other Objective-C type, each property has a type specification and a name. Listing 5-1 illustrates the declaration of a simple property. Listing 5-1

Declaring a simple property

@interface MyClass : NSObject { float value; } @property float value; @end

You can think of a property declaration as being equivalent to declaring two accessor methods. Thus @property float value;

is equivalent to: - (float)value; - (void)setValue:(float)newValue;

A property declaration, however, provides additional information about how the accessor methods are implemented (as described in “Property Declaration Attributes” (page 70)).

Property Declaration Attributes You can decorate a property with attributes by using the form @property(attribute [, attribute2, ...]). Like methods, properties are scoped to their enclosing interface declaration. For property declarations that use a comma delimited list of variable names, the property attributes apply to all of the named properties. If you use the @synthesize directive to tell the compiler to create the accessor methods, the code it generates matches the specification given by the keywords. If you implement the accessor methods yourself, you should ensure that it matches the specification (for example, if you specify copy you must make sure that you do copy the input value in the setter method).

Accessor Method Names The default names for the getter and setter methods associated with a property are propertyName and setPropertyName: respectively—for example, given a property “foo”, the accessors would be foo and setFoo:. The following attributes allow you to specify custom names instead. They are both optional and can appear with any other attribute (except for readonly in the case of setter=).

70

Property Declaration and Implementation 2010-12-08 | © 2010 Apple Inc. All Rights Reserved.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.