01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Adding new instance variables<br />

127<br />

superclass of a class is the class that a new class is subclassing. Although this is the most<br />

straightforward example of subclassing, you can subclass in many different ways, with<br />

subtle distinctions between them.<br />

6.2 Adding new instance variables<br />

Now that your class files are created and their header files filled in, you can continue<br />

to implement them. You need to start filling in the .m files for all the classes you created.<br />

The .h file simply outlines what types of operations and variables a class uses.<br />

The .m file is the piece of code that implements the creation of these variables and<br />

the execution of the declared methods.<br />

Any instance variable that your subclass has must be initialized. Right now, these<br />

variables have types and names, but you must tell the application to allocate some<br />

space in memory for them and to connect these variable names to actual memory.<br />

This is usually done in two parts. First, the variable needs to have space allocated for it,<br />

using the alloc method. Second, the variable must be initialized, using the init<br />

method of your class. Every class should have an init method where the instance variables<br />

and general setup for the class are performed. Let’s set up the init methods for<br />

your new classes.<br />

Go into the Person.m file. You’ll see an essentially blank class. You’ll make the initialization<br />

method for this class so that you can use it in your project. Enter the code<br />

from the following listing into Person.m.<br />

Listing 6.4<br />

Creating the init method for the Person class<br />

#import "Person.h"<br />

@implementation Person<br />

- (id)init {<br />

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

name = @"Person";<br />

age = [NSNumber numberWithInt:-1];<br />

gender = Male;<br />

}<br />

b<br />

A blank initialization<br />

method<br />

}<br />

return self;<br />

- (id)initWithName:(NSString *)_name {<br />

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

name = _name;<br />

age = [NSNumber numberWithInt:-1];<br />

gender = Male;<br />

}<br />

c<br />

Method takes<br />

name for person<br />

}<br />

return self;<br />

- (id)initWithAge:(NSNumber *)_age {<br />

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

d<br />

Method takes<br />

age for person

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

Saved successfully!

Ooh no, something went wrong!