Category is one of the most commonly used functions in objective-c.
The category can add methods to existing classes without adding a subclass.
The standard syntax format for the category interface is as follows:
[CPP]View Plaincopy
- #import "class name. h"
- @interface class name (category name)
- Declaration of the new method
- @end
The categories are implemented as follows:
[CPP]View Plaincopy
- #import "class name Category name. h"
- @implementation class name (category name)
- New Method implementation
- @end
This is very similar to the definition of a class, except that the category has no parent class , and that there is a category name in parentheses. Names can be taken casually.
For example: if we want to add a method to the NSString to determine whether it is a URL, then you can do this:
[CPP]View Plaincopy
- #import ...
- @interface NSString (Utilities)
- -(BOOL) Isurl;
- @end
Category implementations:
[CPP]View Plaincopy
- #import "NSStringUtilities.h"
- @implementation NSString (Utilities)
- -(BOOL) isurl{
- if ([Self hasprefix:@"/http"])
- return YES;
- Else
- return NO;
- }
- @end
How to use:
[CPP]View Plaincopy
- nsstring* string1 = @"http://www.csdn.net";
- nsstring* string2 = @"Pixar";
- if ([string1 Isurl])
- NSLog (@"string1 is a URL");
- Else
- NSLog (@"string1 is not a URL");
- if ([string2 Isurl])
- NSLog (@"string2 is a URL");
- Else
- NSLog (@"string2 is not a URL");
Objective-c Category (categories)