Graphics Programs Reference
In-Depth Information
What if you want to create an entirely new instance method, one that you are not overrid-
ing from the superclass? You declare the new method in the header file and define it in the
implementation file. A good method to begin with is an object's initializer.
Initializers
At the beginning of this chapter, we discussed how an instance is created: its class is sent
the message alloc , which creates an instance of that class and returns a pointer to it, and
then that instance is sent the message init , which gives its instance variables initial val-
ues. As you start to write more complicated classes, you will want to create initialization
methods, or initializers , that are like init but take arguments that the object can use to
initialize itself. For example, the BNRItem class would be much cleaner if we could pass
one or more of its instance variables as part of the initialization process.
To cover the different possible initialization scenarios, many classes have more than one
initializer. Each initializer begins with the word init . Naming initializers this way
doesn't make these methods different from other instance methods; it is only a naming
convention. However, the Objective-C community is all about naming conventions, which
you should strictly adhere to. (Seriously. Disregarding naming conventions in Objective-C
results in problems that are worse than most beginners would imagine.)
For each class, regardless of how many initialization methods there are, one method is
chosen as the designated initializer . The designated initializer makes sure that every in-
stance variable of an object is valid. (“Valid” has different meanings, but in this context it
means “when you send messages to this object after initializing it, you can predict the out-
come and nothing bad will happen.”)
Typically, the designated initializer has parameters for the most important and frequently
used instance variables of an object. The BNRItem class has four instance variables, but
only three are writeable. Therefore, BNRItem 's designated initializer should accept three
arguments. In BNRItem.h , declare the designated initializer:
NSDate *dateCreated;
}
- (id)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber;
- (void)setItemName:(NSString *)str;
Search WWH ::




Custom Search