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.

Runtime type information<br />

173<br />

8.4.3 Adding new methods to a class at runtime<br />

The <strong>Objective</strong>-C statement [CTRentalProperty class] returns a Class object that<br />

represents the CTRentalProperty class. With <strong>Objective</strong>-C’s dynamic features, it’s possible<br />

to add or remove methods, protocols, and properties from a class by interacting<br />

with this object at runtime.<br />

We demonstrate how to dynamically add a new method implementation to an<br />

existing class by responding to the class’s resolveInstanceMethod: message. This is<br />

another method invoked on an object when a message sent to it doesn’t find a matching<br />

method implementation.<br />

At the lowest level of the <strong>Objective</strong>-C runtime, an <strong>Objective</strong>-C method is a C function<br />

that takes, at a minimum, two additional arguments named self and _cmd (as discussed<br />

previously). Once a suitable function is developed, it can be registered as a method of<br />

an <strong>Objective</strong>-C class using a function called class_addMethod:. Add the following code<br />

to CTRentalProperty.m in the current version of the Rental Manager application:<br />

void aSimpleDynamicMethodIMP(id self, SEL _cmd) {<br />

NSLog(@"You called a method named %@", NSStringFromSelector(_cmd));<br />

}<br />

+ (BOOL)resolveInstanceMethod:(SEL)sel {<br />

if (sel == @selector(aSimpleDynamicMethod)) {<br />

NSLog(@"Adding a method named %@ to class %@",<br />

NSStringFromSelector(sel),<br />

NSStringFromClass([self class]));<br />

class_addMethod([self class],<br />

sel,<br />

(IMP)aSimpleDynamicMethodIMP,<br />

"v@:");<br />

return YES;<br />

}<br />

}<br />

return [super resolveInstanceMethod:sel];<br />

In the current version of the Rental Manager application, you can then add the<br />

following calls to a convenient location, such as the RootViewController’s viewDid-<br />

Load method:<br />

id house = [CTRentalProperty rentalPropertyOfType:TownHouse<br />

rentingFor:420.0f<br />

atAddress:@"13 Waverly Crescent, Sumner"];<br />

[house aSimpleDynamicMethod];<br />

[house aSimpleDynamicMethod];<br />

[house aSimpleDynamicMethod];<br />

[house aSimpleDynamicMethod];<br />

[house aSimpleDynamicMethod];<br />

When this code is executed, you should notice that the debug console lists the following<br />

content:<br />

Adding a method named aSimpleDynamicMethod to class CTRentalProperty<br />

You called a method named aSimpleDynamicMethod

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

Saved successfully!

Ooh no, something went wrong!