What
Categories are objective-c’s way of allowing you to add methods to an existing class without having to touch it’s source.
For example, say we wished had a method on NSString that decorated our string with some pretty output.
- (NSString *) decorate { return [NSString stringWithFormat:@"=== %@ ===", self];; }
And we wished we could call it directly on NSString like this:
NSLog(@"%@", @"Booya".decorate);
Outputs:
=== Booya ===
Categories allow us to do that. Here’s how.
How
The format of a category is the ClassName you are extending, followed by the name you want to give your category (i.e. “Utils”).
#import "ClassName.h" @interface ClassName ( CategoryName ) // method declarations @end
To make a new category in Xcode we basically create a new class. Go:
New File (Command + N).
Select ‘Objective-C category’.
Specify the class you want to add a category onto (i.e. NSString).
Then add your category method to your .h file.
#import <Foundation/Foundation.h> @interface NSString (Utils) - (NSString *) decorate; @end
And your implementation to you .m file.
#import "NSString+Utils.h" @implementation NSString (Utils) - (NSString *) decorate { return [NSString stringWithFormat:@"=== %@ ===", self];; } @end
Now you can go to the class where you want to use the extension, import your category header and make your method call.
#import "NSString+Utils.h" - (IBAction)tapMePressed:(id)sender { NSLog(@"%@", @"Booya".decorate); }
That’s it!
Links that help
Apple documentation on category
Aug 30, 2012 @ 14:28:46
Reblogged this on Gigable – Tech Blog.