Extending classes with categories in Xcode for iOS


A category extends the functionality of Apple's in-built classes without subclassing. We do this by first of all creating a header and implementation file for the category by using the Objective-C category template. Next we add our method to the category's .m file:

#import "UIColor+seeThroughBlue.h"

@implementation UIColor (seeThroughBlue)
+(UIColor*)seeThroughBlueColor {
    return [UIColor colorWithRed:0 green:0 blue:1 alpha:0.5];
}
@end

(Note: I'm extending UIColor and have called the category seeThroughBlue - Xcode has added UIColor+ to the filenames for convenience)

Next we need to add this method to the .h file:


#import <UIKit/UIKit.h>

@interface UIColor (seeThroughBlue)
+(UIColor*)seeThroughBlueColor;
@end


You'll notice that the name of the category (seeThroughBlue) isn't the same as the filename, because it doesn't need to be.

Finally, to make it globally available we add it to the appName-Prefix.pch file (in your supporting files folder):


#import <Availability.h>

#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/ Foundation.h>
    #import "UIColor+seeThroughBlue.h"

#endif

Now if we want to call the new method from our category we can do so without importing anything extra. For example inside one of our view controller methods we might write:

self.view.backgroundColor=[UIColor seeThroughBlueColor];

Endorse  on Coderwall

Comments