Have you ever wished you could add a method to an existing class that you don’t have the code for?
Well, now you can, with categories.
Categories let you extend an existing class with whatever method you deem fit. It is pretty useful to add helper methods to other classes that help parse the date in a way the class make perhaps did not intend. You can also use it to split up your own classes so that if you have some big omni-class that does several things, you can opt in to just the parts you want by only including those categories.
To add a category, go to File -> New File…, and select “Objective-C category” from the “Cocoa Touch” tab under iOS. This will bring up an additional window, where you can name the Category in the “Category” textfield. You then type or select the class you want to add it to, and it will output 2 very simple files. For my example, I am adding a helper method to NSDate to tell me if something is in the past. It is originally from this Stack Overflow question, answered by Matt Galloway (@mattjgalloway on twitter). So if name the category “Helper”, I would have these files generated for me.
NSDate+Helper.h
@interface NSDate (Helper)
@end
NSDate+Helper.m
#import "NSDate+Helper.h"
@implementation NSDate (Helper)
@end
Pretty simple. Now to add my method to tell me if this date is in the past, I just make a method like normal, and add its prototype to the header file, so I end with.
NSDate+Helper.h
@interface NSDate (Helper)
-(BOOL)isInPast;
@end
NSDate+Helper.m
@implementation NSDate (Helper)
-(BOOL)isInPast
{
NSDate *testTime = self;
if ([testTime timeIntervalSinceNow] < 0.0)
{
return YES;
}else
{
return NO;
}
}
@end
And that is all there is to it. The code itself just asks what the time interval since now is, and if it is negative, that means it is in the past. Now in any class that I want to use this, I have to import this category’s header file, and then I can ask an NSDate if it is in the past.
You import the category:
#import "NSDate+Helper.h"
and somewhere in your program you could test it like this:
NSDate *someTime = [NSDate date];
if ([someTime isInPast]) {
NSLog(@"It's in the past!");
} else
{
NSLog(@"It is yet to come!");
}
And this code snippet simply grabs the current time, puts it in to the object “someTime.” Then it asks “someTime” right afterwards if it is in the past, and NSLogs an appropriate response.
Categories are a very powerful tool, so be careful how you use them. Also, don’t use them to override a method, you should subclass the parent class if you want to do that.
I hope you found this article helpful. If you did, don’t hesitate to share this post on twitter or your social media of choice. The blog is still pretty new, and every share helps. Of course, if you have any questions, don’t hesitate to contact me on twitter @CodingExplorer, and I’ll see what I can do. Thanks!