CATEGORIES
A category in Objective-C enables you to add methods to an existing class without the need to subclass it. You can also use a category to override the implementation of an existing class.
NOTE In some languages (such as C#), a category is known as an extension method.
For example, imagine you want to test whether a string contains a valid e-mail address. You can add an isEmail method to the NSString class so that you can call the isEmail method on any NSString instance, like this:
NSString *email = @“weimenglee@gmail.com”; if ([email isEmail]) { //... }
To do so, simply create a new class file and code it as follows:
//---Utils.h--- #import <Foundation/Foundation.h> //---NSString is the class you are extending--- @interface NSString (Utilities) //---the method you are adding to the NSString class--- -(BOOL) isEmail; @end
Basically, it looks the same as declaring a new class except that it does not inherit from any other class. The stringUtils is a name that identifies the category you are adding, and you can use any name you want.
Next, you need to implement the method(s) you are adding:
//---Utils.m---
#import “Utils.h”
@implementation NSString (Utilities)
- (BOOL) isEmail {
NSString *emailRegEx = @“(?:[a-z0-9!#$%\\&‘*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&’*+/=?\\^_`{|}” @“~-]+)*|\”(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\“ @”x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\“)@(?:(?:[a-z0-9](?:[a-” ...
Get Beginning iOS 5 Application Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.