Skip to Content
Beginning iOS 5 Application Development
book

Beginning iOS 5 Application Development

by Wei-Meng Lee
January 2012
Beginner content levelBeginner
655 pages
16h 35m
English
Wrox
Content preview from Beginning iOS 5 Application Development

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.

image 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-” ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering iOS 12 Programming - Third Edition

Mastering iOS 12 Programming - Third Edition

Donny Wals
What Successful Project Managers Do

What Successful Project Managers Do

W. Scott Cameron, Jeffrey S. Russell, Edward J. Hoffman, Alexander Laufer

Publisher Resources

ISBN: 9781118144251Purchase book