background image
Declare Member Variables
The two variables are defined between the braces of the converter class. Define the variables:
1.
If
Converter.h
is not already open for editing, double-click
Converter.h
in the Classes group of the
Groups & Files menu. This opens the file in an editor window.
2.
Insert the highlighted line in Listing 3-1 into
Converter.h
Listing 3-1
Declaration of the member variables in
Converter.h
#import <Cocoa/Cocoa.h>
@interface Converter : NSObject {
float sourceCurrencyAmount, rate;
}
Declared Properties and Accessor Methods
Objects encapsulate data, as explained in
"Classes and Objects"
(page 11). The scope of variables in an object
is limited to that particular object--that is, the instance of that class. One instance of a customer class, for
example, can only see its own data, not the data of any customer object. But say a specific customer needs
to compare itself with another customer. In order for this to be possible, classes supply accessor methods
to read and write to the data an object encapsulates. This gives the classes the discretion of what data they
wish to share. For example, if a specific class does not want to share certain variables it encapsulates with
another class, and only wants to use them for internal use, it can simply not have accessor methods for that
variable. This is also true if a class wants external entities to have read-only access to its variables. In that
case, a class will have methods that get values, but no methods that set values.
Objective-C 2.0 provides a feature called declared properties. A property declaration is, effectively, a shorthand
for declaring the setter and getter for an attribute of an instance of a class. In addition to the declaration
itself, there are directives to instruct the compiler to synthesize the accessors and to inform the compiler
that you will provide the methods yourself at runtime. There are two parts to a property, its declaration and
its implementation.
You declare a property as follows:
@property(attributes) Type variableNameList;
where attributes is a comma-separated list of keywords such as
readwrite
and
copy
, for example:
@property(copy) NSString *name;
For the purposes of Currency Converter, add the following line after the closing brace of the converter class
in
Converter.h
:
@property(readwrite) float sourceCurrencyAmount, rate;
At compile time, the compiler treats this as if you had declared the following methods:
- (float)sourceCurrencyAmount;
- (void)setSourceCurrencyAmount:(float)newSourceCurrencyAmount;
- (float)rate;
- (void)setRate:(float)newRate;
22
Declare the Model Interface
2007-10-31 | © 2007 Apple Inc. All Rights Reserved.
CHAPTER 3
Defining the Model