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:
#import <Foundation/Foundation.h> @interface NSString (VowelCounting) - (int)vowelCount; @end
Now implement the method in NSString+VowelCount.m:
#import "NSString+VowelCounting.h" @implementation NSString (VowelCounting) - (int)vowelCount { NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"aeiouyAEIOUY"]; NSUInteger count = [self length]; int sum = 0; for (int i = 0; i < count; i++) { unichar c = [self characterAtIndex:i]; if ([charSet characterIsMember:c]) { sum++; } } return sum; } @end
Now use the new method in main.m:
#import <Foundation/Foundation.h> #import "NSString+VowelCounting.h" int main (int argc, const char * argv[]) { @autorelease { NSString *string = @"Hello, World!"; NSLog(@"%@ has %d vowels", string, [string vowelCount]); } return 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.