Graphics Programs Reference
In-Depth Information
turn an object of their type (like
stringWithFormat:
and
randomItem
) are called
convenience methods
.
Notice the use of
self
in
randomItem
. Because
randomItem
is a class method,
self
refers to the
BNRItem
class itself instead of an instance. Class methods should use
self
in convenience methods instead of their class name so that a subclass can be sent
the same message. In this case, if you create a subclass of
BNRItem
, you can send that
subclass the message
randomItem
. Using
self
(instead of
BNRItem
) will allocate an
instance of the class that was sent the message and set the instance's
isa
pointer to that
class.
Testing your subclass
Open
main.m
. Delete the code that previously created and logged a single
BNRItem
.
Then add
BNRItem
instances to the array and log them instead. Change your
main
func-
tion to look just like this:
#import <Foundation/Foundation.h>
#import "BNRItem.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *items = [[NSMutableArray alloc] init];
BNRItem *p = [[BNRItem alloc] initWithItemName:@"Red Sofa"
valueInDollars:100
serialNumber:@"A1B2C"];
NSLog(@"%@", p);
for (int i = 0; i < 10; i++) {
BNRItem *p = [BNRItem randomItem];
[items addObject:p];
}
for (int i = 0; i < [items count]; i++) {
NSLog(@"%@", [items objectAtIndex:i]);
}
items = nil;
}
return 0;
}