05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

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.

500<br />

CHAPTER 26 MAC <strong>OS</strong> X DEVELOPMENT: OBJECTIVE-C<br />

@implementation NSString (BMString)<br />

- (NSString *)stringByPrependingString:(NSString *)aString;<br />

{<br />

return [aString stringByAppendingString:self];<br />

}<br />

@end<br />

Now prepending a string works as expected:<br />

NSString *greeting = @", world!";<br />

greeting = [greeting stringByPrependingString:@"Hello"];<br />

NSLog(greeting);<br />

Hello, world!<br />

Unlike a subclass, we have access to everything in the NSString class, including private members.<br />

Indeed, when you’re writing a category, the hardest thing to remember is that you’re inside<br />

the class you’re categorizing. Try not to let the power go to your head, or the next section will<br />

really blow your mind.<br />

Method Swizzling<br />

It’s one thing to add methods to a class, but the inheritance model offers something categories<br />

don’t. Namely, a subclass can override a superclass’s implementation. That is, it doesn’t just add<br />

behavior; it can change behavior. Objective-C lets you do this and more. Since method implementations<br />

are data, you can swap any class’s implementation with your own, a trick called<br />

swizzling.<br />

For example, consider the description method, as implemented by NSXMLNode. It just spits out<br />

raw XML, without any whitespace. I’ll show you what I mean. Consider the following snippet<br />

of XML, a bit of syndicated web content created by iWeb:<br />

<br />

<br />

<br />

My Blog<br />

http://www.worldofkevin.com/Site/Blog/Blog.html<br />

Welcome to my blog: Alit, Enit, Laore, Eros Vel, Exer Dolorer,<br />

Niam Lut.<br />

iWeb 1.1.2<br />

<br />

http://www.worldofkevin.com/Site/Blog/Blog_files/200206373-3-a.png<br />

<br />

My Blog<br />

http://www.worldofkevin.com/Site/Blog/Blog.html<br />

<br />

<br />

Red Vines: the perfect super food<br />

http://www.worldofkevin.com/Site/Blog/88DD8356-E484-44DD-9419-<br />

AE9F936E8BAD.html<br />

http://www.worldofkevin.com/Site/Blog/88DD8356-E484-44DD-9419-<br />

AE9F936E8BAD.html<br />

Mon, 20 Aug 2007 10:48:11 -0700<br />

&lt;a href='http://www.worldofkevin.com/Site/Blog/<br />

88DD8356-E484-44DD-9419-AE9F936E8BAD_files/FD004359-1.jpg'>&lt;img

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

Saved successfully!

Ooh no, something went wrong!