This is particularly useful because you can add methods to built-in objects. If you want to add a method to all instances of NSString in your application, you just add a category. There's no need to get everything to use a custom subclass.
For example, if I wanted to add a method to NSString to determine if the contents is a URL, it would look like this:
#importThis is very similar to a class declaration. The differences are that there is no super class listed, and there's a name for the category in parenthesis. The name can be whatever you want, though it should communicate what the methods inside do.@interface NSString (Utilities) - (BOOL) isURL; @end
Here's the implementation. Keep in mind this is not a good implementation of URL detection. We're just trying to get the concept of categories across:
#import "NSString-Utilities.h" @implementation NSString (Utilities) - (BOOL) isURL { if ( [self hasPrefix:@"http://"] ) return YES; else return NO; } @endNow you can use this method on any NSString. The following code will print "string1 is a URL" in the console:
NSString* string1 = @"http://pixar.com/"; NSString* string2 = @"Pixar"; if ( [string1 isURL] ) NSLog (@"string1 is a URL"); if ( [string2 isURL] ) NSLog (@"string2 is a URL");Unlike subclasses, categories can't add instance variables. You can, however, use categories to override existing methods in classes, but you should do so very carefully.
Remember, when you make changes to a class using a category, it affects all instances of that class throughout the application.
No comments:
Post a Comment