Graphics Programs Reference
In-Depth Information
Properties
Each time we've added an instance variable to BNRItem , we've declared and implemen-
ted a pair of accessor methods. Now we're going to see how to use properties instead.
Properties are a convenient alternative to writing out accessors for instance variables - one
that saves a lot of typing and makes your class files much clearer to read.
Declaring properties
A property is declared in the interface of a class where methods are declared. A property
declaration has the following form:
@property NSString *itemName;
When you declare a property, you are implicitly declaring a setter and a getter for the in-
stance variable of the same name. So the above line of code is equivalent to the following:
- (void)setItemName:(NSString *)str;
- (NSString *)itemName;
Each property has a set of attributes that describe the behavior of the accessor methods.
The attributes are declared in parentheses after the @property directive. Here is an ex-
ample:
@property (nonatomic, readwrite, strong) NSString *itemName;
There are three property attributes. Each attribute has two or three options, one of which is
the default and does not have to explicitly declared.
The first attribute of a property has two options: nonatomic or atomic . This attribute
has to do with multi-threaded applications and is outside the scope of this topic. Most
Objective-C programmers typically use nonatomic : we do at Big Nerd Ranch, and so
does Apple. In this topic, we'll use nonatomic for all properties.
Let's change BNRItem to use properties instead of accessor methods. In BNRItem.h , re-
place all of your accessor methods with properties that are nonatomic.
- (id)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber;
- (void)setItemName:(NSString *)str;
Search WWH ::




Custom Search