Graphics Programs Reference
In-Depth Information
Accessor methods
Now that you have instance variables, you need a way to get and set their values. In
object-oriented languages, we call methods that get and set instance variables accessors .
Individually, we call them getters and setters . Without these methods, an object cannot ac-
cess the instance variables of another object.
Accessor methods look like this:
// a getter method
- (NSString *)itemName
{
// Return a pointer to the object this BNRItem calls its itemName
return itemName;
}
// a setter method
- (void)setItemName:(NSString *)newItemName
{
// Change the instance variable to point at another string,
// this BNRItem will now call this new string its itemName
itemName = newItemName;
}
Then, if you wanted to access (set or get) a BNRItem 's itemName , you would send the
BNRItem one of these messages:
// Create a new BNRItem instance
BNRItem *p = [[BNRItem alloc] init];
// Set itemName to a new NSString
[p setItemName:@"Red Sofa"];
// Get the pointer of the BNRItem's itemName
NSString *str = [p itemName];
// Print that object
NSLog(@"%@", str); // This would print "Red Sofa"
In Objective-C, the name of a setter method is set plus the name of the instance variable
it is changing - in this case, setItemName: . In other languages, the name of the getter
method would likely be getItemName . However, in Objective-C, the name of the getter
method is just the name of the instance variable. Some of the cooler parts of the Cocoa
Touch library make the assumption that your classes follow this convention; therefore,
stylish Cocoa Touch programmers always do so.
In BNRItem.h , declare accessor methods for the instance variables of BNRItem . You
will need getters and setters for valueInDollars , itemName , and serialNumber .
For dateCreated , you only need a getter method.
Search WWH ::




Custom Search