P. 1
The Objective-C 2.0 Programming Language

The Objective-C 2.0 Programming Language

|Views: 14|Likes:
Published by fpereira2006

More info:

Published by: fpereira2006 on Sep 03, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

05/24/2012

pdf

text

original

You can add methods to a class by declaring them in an interface file under a category name and defining
them in an implementation file under the same name. The category name indicates that the methods are
additionstoaclassdeclaredelsewhere,notanewclass.Youcannot,however,useacategorytoaddadditional
instance variables to a class.

Themethodsthecategoryaddsbecomepartoftheclasstype.Forexample,methodsaddedtotheNSArray
classinacategoryareamongthemethodsthecompilerexpectsanNSArrayinstancetohaveinitsrepertoire.
Methods added to theNSArray class in a subclass are not included in theNSArray type. (This matters only
for statically typed objects, since static typing is the only way the compiler can know an object’s class.)

Category methods can do anything that methods defined in the class proper can do. At runtime, there’s no
difference. The methods the category adds to the class are inherited by all the class’s subclasses, just like
other methods.

Thedeclarationofacategoryinterfacelooksverymuchlikeaclassinterfacedeclaration—exceptthecategory
nameislistedwithinparenthesesaftertheclassnameandthesuperclassisn’tmentioned.Unlessitsmethods
don’t access any instance variables of the class, the category must import the interface file for the class it
extends:

#import "ClassName.h"

@interface ClassName ( CategoryName )
// method declarations
@end

The implementation, as usual, imports its own interface. A common naming convention is that the base file
name of the category is the name of the class the category extends followed by “+” followed by the name
ofthecategory.Acategoryimplementation(inafilenamedClassName+CategoryName.m)mighttherefore
look like this:

#import "ClassName+CategoryName.h"

@implementation ClassName ( CategoryName )
// method definitions
@end

Adding Methods to Classes

69

2009-02-04 | © 2009 Apple Inc. All Rights Reserved.

CHAPTER5

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->