Last Updated: February 25, 2016
· anthonylevings
Speechrocket4 square

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];

(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)

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."

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


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];

And that's all, no need to import the category into the view controller .h and .m files.

Full blogpost: http://sketchytech.blogspot.co.uk/2012/09/extending-classes-with-categories-in.html

Say Thanks

2 Responses
Add your response

0 m3jgdhwjqdd2zi2xmgpjdcoln7ssn82xu6dgdco3wumgwxrkzfdabgyfsfvtcbdhzg0p6lnktqe8

Thanks ,Nice and well explained tutorial written by you.I've one question that How can I come up with Creating Category on UIActionSheet ,and Would like to add UIPickerView to that UIActionSheet .(I would like to reduce code of controller and finally bear with iOS 7)

over 1 year ago ·
Speechrocket4 square

Taking a brief look at StackOverflow, it looks like the thing you are asking isn't possible - e.g. http://stackoverflow.com/questions/1262574/add-uipickerview-a-button-in-action-sheet-how - and that you need to find some other way around the problem.

over 1 year ago ·