Graphics Programs Reference
In-Depth Information
Using Initializers
Currently, the code in main.m sends the message init to the new instance of
BNRItem . With these new initializer methods, this message will run the init method
you just implemented in BNRItem , which calls the designated initializer
) initWithItemName:valueInDollars:serialNumber: ) and passes default
values. Let's make sure this works as intended.
In main.m , log the BNRItem to the console after it is initialized but before the setter
messages are sent.
BNRItem *p = [[BNRItem alloc] init];
NSLog(@"%@", p);
// This creates a new NSString, "Red Sofa", and gives it to the BNRItem
[p setItemName:@"Red Sofa"];
Build and run the application. Notice that the console spits out the following messages:
Item (): Worth $0, recorded on 2011-07-19 18:56:42 +0000
Red Sofa (A1B2C): Worth $100, recorded on 2011-07-19 18:56:42 +0000
Now replace the code that initializes the BNRItem and the code sets its instance variables
with a single message send using the designated initializer. Also, get rid of the code that
populates the NSMutableArray with strings and prints them to the console. In
main.m , make the following changes:
#import <Foundation/Foundation.h>
#import "BNRItem.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *items = [[NSMutableArray alloc] init];
[items addObject:@"One"];
[items addObject:@"Two"];
[items addObject:@"Three"];
[items insertObject:@"Zero" atIndex:0];
for (int i = 0; i < [items count]; i++) {
NSLog(@"%@", [items objectAtIndex:i]);
}
BNRItem *p = [[BNRItem alloc] init];
NSLog(@"%@ %@ %@ %d", [p itemName], [p dateCreated],
[p serialNumber], [p valueInDollars]);
BNRItem *p = [[BNRItem alloc] initWithItemName:@"Red Sofa"
valueInDollars:100
serialNumber:@"A1B2C"];
NSLog(@"%@", p);
 
Search WWH ::




Custom Search