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.

Overriding methods<br />

131<br />

}<br />

return gender;<br />

}<br />

return -1;<br />

- (void)setName:(NSString *)_name {<br />

name = _name;<br />

}<br />

- (void)setAge:(NSNumber *)_age {<br />

age = _age;<br />

}<br />

- (void)setGender:(Gender)_gender {<br />

gender = _gender;<br />

}<br />

Getter and setter methods are pretty self-explanatory. Getter methods return an<br />

instance variable with the same name. Setter methods take in an object and set it to<br />

an instance variable. The only point of note here is that in the getter methods, make<br />

sure to check if the variables exist. If the name getter was called, for instance, and the<br />

name was never set, an error would be returned without the check. If the name didn’t<br />

exist, a nil value would be returned.<br />

This method is more time consuming than the method we examine next, but it<br />

also allows a nice cutoff point to perform operations when a class’s instance variables<br />

are requested. If, for instance, you want to count the number of times a variable is<br />

called or set, you can do so with these methods.<br />

This is the classic way that getters and setters used to be created, but most developers<br />

now use properties to create them. Properties were introduced by Apple to automatically<br />

generate these very common methods. Refer to section 5.4 for more<br />

information on this automated approach.<br />

6.4 Overriding methods<br />

Overriding methods is another important aspect of subclassing in <strong>Objective</strong>-C. Just as<br />

a subclass of any class retains the class’s instance variables, it also gains access to all the<br />

class’s instance methods. If you call a method to a class and the compiler sees that a<br />

method with that name doesn’t exist in the class, it goes to the superclass and checks<br />

for the method there (see figure 6.1).<br />

Generally, method overriding is the act of replacing a method from the parent<br />

class with a method that does something different. This is commonly done when creating<br />

class structures, because methods may need to perform slightly differently in a<br />

subclass than they do in the class in which they’re first declared.<br />

Let’s do some method overriding in your new classes. The NSObject class has a<br />

method called<br />

- (NSString)description;<br />

This is a helpful class to override when creating custom classes. It’s likely that during<br />

development you’ll be taking advantage of the NSLog operation to help debug your

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

Saved successfully!

Ooh no, something went wrong!