01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating and destroying objects<br />

117<br />

correctly configure the object. Typically, a class provides one or more specialized initialization<br />

methods. These methods are commonly named using the form initWith-<br />

XYZ:, where XYZ is replaced with a description of any additional parameters required<br />

to properly initialize the object.<br />

As an example, add the following method declaration to the @interface section of<br />

the CTRentalProperty class:<br />

- (id)initWithAddress:(NSString *)newAddress<br />

rentalPrice:(float)newRentalPrice<br />

andType:(PropertyType)newPropertyType;<br />

This instance method enables you to provide a new address, rental price, and property<br />

type for the object about to be initialized. The next step is to provide an implementation<br />

for the method in the @implementation section of the CTRentalProperty<br />

class. Do this by adding the following code.<br />

Listing 5.5<br />

Implementing a custom initialization method for CTRentalProperty<br />

- (id)initWithAddress:(NSString *)newAddress<br />

rentalPrice:(float)newRentalPrice<br />

andType:(PropertyType)newPropertyType<br />

{<br />

if ((self = [super init])) {<br />

self.address = newAddress;<br />

self.rentalPrice = newRentalPrice;<br />

self.propertyType = newPropertyType;<br />

}<br />

}<br />

return self;<br />

The main part of this method sets the various properties of the object to the new values<br />

specified by the parameters. There are, however, a couple of additional features in<br />

this listing that deserve extra attention.<br />

The if statement performs a number of important steps in a single, condensed<br />

line of source code. Working from right to left, it first sends the init message to<br />

super. super is a keyword, similar to self, that enables you to send messages to the<br />

superclass. Before you initialize any of your own instance variables, it’s important to<br />

provide your superclass a chance to initialize its own state.<br />

The object returned by the superclass’s init method is then assigned to self in<br />

case it has substituted your object for another. You then check this value to ensure it<br />

isn’t nil, which would indicate the superclass has determined it can’t successfully initialize<br />

the object. If you prefer, you could expand these steps into two separate statements,<br />

as follows:<br />

self = [super init];<br />

if (self != nil) {<br />

...<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!