Graphics Programs Reference
In-Depth Information
Instance methods
Not all instance methods are accessors. You will regularly find yourself wanting to send
messages to instances that perform other tasks. One such message is
description
.
You can implement this method in
BNRItem
to return a string that describes a
BNRItem
instance. Because
BNRItem
is a subclass of
NSObject
(the class that originally de-
clares the
description
method), when you re-implement
description
in the
BNRItem
class, you are
overriding
it. When overriding a method, all you need to do is
define it in the implementation file; you do not need to declare it in the header file because
it has already been declared by the superclass.
In
BNRItem.m
, override the
description
method. This new code can go anywhere
between
@implementation
and
@end
, as long as it is not inside the curly brackets of
an existing method.
- (NSString *)description
{
NSString *descriptionString =
[[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, recorded on %@",
itemName,
serialNumber,
valueInDollars,
dateCreated];
return descriptionString;
}
Now whenever you send the message
description
to an instance of
BNRItem
, it will
return an
NSString
that describes that instance. In
main.m
, substitute this new method
into the
NSLog
that prints out the instance variables of the
BNRItem
.
[p setValueInDollars:100];
NSLog(@"%@ %@ %@ %d", [p itemName], [p dateCreated],
[p serialNumber], [p valueInDollars]);
// Remember, an NSLog with %@ as the token will print the
// description of the corresponding argument
NSLog(@"%@", p);
items = nil;
Build and run the application and check your results in the log navigator. You should see a
log statement that looks like this:
Red Sofa (A1B2C): Worth $100, recorded on (null)