Recently, I’ve been trying to subclass NSString and add a method that I’ll be using in my application. After reading “Categories” by John Muchow, I decided to use categories. Instead of creating a new class, I would just add methods to an existing class.
Here is a simple example adding a newFunction to NSString. In your header file, you add “(CategoryName)” to the interface and declare the function you wanted to add.
@interface NSString (CategoryName)
- (NSString *)newFunction;
@end
You then implement newFunction in your implementation file.
@implementation NSString (CategoryName)
- (NSString *)newFunction {
// write your code here
}
@end
Now, if you import your header file in your code, you could just call “newFunction” just like any other function of NSString.
NSString *testString = [[NSString alloc] init];
[testString setString:@"String"];
[testString newFunction]; // this will call your function
[testString dealloc];
Of course, there will be cases when you need to subclass like when you want to add properties to a class, among others.