31
Categories

Categories let a programmer add methods to any existing class. For example, Apple gave us the class NSString. We don’t get the source code to that class, but categories give us the ability to add new methods to NSString.

Create a new Foundation Command Line Tool called VowelCounter. Then create a new file that is an Objective-C category. Name the category VowelCounting and make it a category on NSString.

Now open NSString+VowelCounting.h and declare a method that you want to add to the NSString class:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​

@​i​n​t​e​r​f​a​c​e​ ​N​S​S​t​r​i​n​g​ ​(​V​o​w​e​l​C​o​u​n​t​i​n​g​)​
-​ ​(​i​n​t​)​v​o​w​e​l​C​o​u​n​t​;​

@​e​n​d​

Now implement the method in NSString+VowelCount.m:

#​i​m​p​o​r​t​ ​"​N​S​S​t​r​i​n​g​+​V​o​w​e​l​C​o​u​n​t​i​n​g​.​h​"​

@​i​m​p​l​e​m​e​n​t​a​t​i​o​n​ ​N​S​S​t​r​i​n​g​ ​(​V​o​w​e​l​C​o​u​n​t​i​n​g​)​

-​ ​(​i​n​t​)​v​o​w​e​l​C​o​u​n​t​
{​
 ​ ​ ​ ​N​S​C​h​a​r​a​c​t​e​r​S​e​t​ ​*​c​h​a​r​S​e​t​ ​=​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​[​N​S​C​h​a​r​a​c​t​e​r​S​e​t​ ​c​h​a​r​a​c​t​e​r​S​e​t​W​i​t​h​C​h​a​r​a​c​t​e​r​s​I​n​S​t​r​i​n​g​:​@​"​a​e​i​o​u​y​A​E​I​O​U​Y​"​]​;​

 ​ ​ ​ ​N​S​U​I​n​t​e​g​e​r​ ​c​o​u​n​t​ ​=​ ​[​s​e​l​f​ ​l​e​n​g​t​h​]​;​
 ​ ​ ​ ​i​n​t​ ​s​u​m​ ​=​ ​0​;​
 ​ ​ ​ ​f​o​r​ ​(​i​n​t​ ​i​ ​=​ ​0​;​ ​i​ ​<​ ​c​o​u​n​t​;​ ​i​+​+​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​u​n​i​c​h​a​r​ ​c​ ​=​ ​[​s​e​l​f​ ​c​h​a​r​a​c​t​e​r​A​t​I​n​d​e​x​:​i​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​i​f​ ​(​[​c​h​a​r​S​e​t​ ​c​h​a​r​a​c​t​e​r​I​s​M​e​m​b​e​r​:​c​]​)​ ​{​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​s​u​m​+​+​;​
 ​ ​ ​ ​ ​ ​ ​ ​}​
 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​s​u​m​;​
}​

@​e​n​d​

Now use the new method in main.m:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​
#​i​m​p​o​r​t​ ​"​N​S​S​t​r​i​n​g​+​V​o​w​e​l​C​o​u​n​t​i​n​g​.​h​"​

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​@​a​u​t​o​r​e​l​e​a​s​e​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​s​t​r​i​n​g​ ​=​ ​@​"​H​e​l​l​o​,​ ​W​o​r​l​d​!​"​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​%​@​ ​h​a​s​ ​%​d​ ​v​o​w​e​l​s​"​,​ ​s​t​r​i​n​g​,​ ​[​s​t​r​i​n​g​ ​v​o​w​e​l​C​o​u​n​t​]​)​;​

 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Build and run the program. Nifty, eh? Categories turn out to be very useful.

It is important to note that only this program has the category. If you want the method available in another program, you must add the file to your project and compile the category in when you build that program.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset