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.

Categories<br />

137<br />

This code tells the compiler that you’re adding to the NSString an interface called<br />

VowelDestroyer. This category adds a method called stringByDestroyingVowels<br />

that takes no parameters and returns an NSString.<br />

You implement the method in VowelDestroyer.m so that it can be called when<br />

this method is called on an NSString object. Insert the following code into Vowel-<br />

Destroyer.m.<br />

Listing 6.10<br />

VowelDestroyer.m<br />

#import "VowelDestroyer.h"<br />

@implementation NSString (VowelDestroyer)<br />

- (NSString *)stringByDestroyingVowels {<br />

NSMutableString *mutableString =<br />

[NSMutableString stringWithString:self];<br />

[mutableString replaceOccurrencesOfString:@"a"<br />

withString:@""<br />

options:NSCaseInsensitiveSearch<br />

range:NSMakeRange(0, [mutableString length])];<br />

[mutableString replaceOccurrencesOfString:@"e"<br />

withString:@""<br />

options:NSCaseInsensitiveSearch<br />

range:NSMakeRange(0, [mutableString length])];<br />

[mutableString replaceOccurrencesOfString:@"i"<br />

withString:@""<br />

options:NSCaseInsensitiveSearch<br />

range:NSMakeRange(0, [mutableString length])];<br />

[mutableString replaceOccurrencesOfString:@"o"<br />

withString:@""<br />

options:NSCaseInsensitiveSearch<br />

range:NSMakeRange(0, [mutableString length])];<br />

[mutableString replaceOccurrencesOfString:@"u"<br />

withString:@""<br />

options:NSCaseInsensitiveSearch<br />

range:NSMakeRange(0, [mutableString length])];<br />

b<br />

Declare category<br />

name<br />

c<br />

Create<br />

NSMutableString<br />

}<br />

return [NSString stringWithString:mutableString];<br />

@end<br />

In this code, you declare the file to be an implementation of NSString again and<br />

declare your category name once more B. Then you implement the method appropriately.<br />

In this case you create a new type of string called an NSMutableString. If you<br />

notice, NSStrings can’t be modified. NSString provides methods that modify a string<br />

and return a whole new one, but NSMutableString can be used to modify an existing<br />

string without having the modification methods return a whole new string. If this<br />

method were to be used a lot in an application, this implementation would be the best<br />

use of memory. After creating the NSMutableString c, you replace each vowel with<br />

an empty string using the replaceOccurrencesOfString:withString:options:<br />

range: method. Using the NSCaseInsensitive option with this method matches both

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

Saved successfully!

Ooh no, something went wrong!