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.

132 CHAPTER 6 Extending classes<br />

applications. NSLog supports C-based placeholders such as %@ and %d. When the %@<br />

placeholder is put in an NSString, the placeholder is filled with what is returned by this<br />

method. You’ll implement this method in your three classes and see it work in an NSLog.<br />

6.4.1 Overriding the description method<br />

Overriding a method is done by simply declaring it in the class in which you would<br />

like to call it. Start in the Person class, go into the Person.m file, and declare the<br />

method shown here:<br />

- (NSString *)description {<br />

if (gender == Male) {<br />

return [NSString stringWithFormat:<br />

@"Hi! I am a man, named %@, who is %@ years old",<br />

name, age];<br />

} else {<br />

return [NSString stringWithFormat:<br />

@"Hi! I am a woman, named %@, who is a %@ years old",<br />

name, age];<br />

}<br />

}<br />

The description method is declared in NSObject. By placing the same method in your<br />

class, you’re telling this class that rather than using the NSObject version of the<br />

description method, you want this method to be called. Now you override the description<br />

methods for both Teacher and Student, taking advantage of Person’s description<br />

method in the ones you create in Student and Teacher so that you can write as little<br />

code as possible:<br />

- (NSString *)description {<br />

if(gender == Male) {<br />

return [NSString stringWithFormat:<br />

@"%@. I am a male currently teaching %@ "<br />

Figure 6.1 The compiler<br />

checking the superclass

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

Saved successfully!

Ooh no, something went wrong!