Sunday, April 3, 2011

Category in Objective C

Category in Objective C is a new concept to C++ developer. The catetory must associate with any existing class, even if the class implementation is not accessible to you. Note that a cateory can not declare additional instance variables for the class. It can only include instance methods.
While category is similar to subclass, the difference is with category, the new methods directly added into the original class without creating a new derived class.

The syntax is

Header file (name convention is "classname+categoryname.h"):
#interface "ClassName.h"

@interface ClassName (CategoryName )
- (int) categoryFunction;
@end


Implementation file (name convention is "classname+categoryname.m"):
#import "classnmae+categoryname.m"

@implementation ClassName (CategoryName )
- (int) categoryFunction {
return 0;
}
@end

Note another Objective C feature: Extension is like cateory but without an name, the extension methods must be implemented in the main @implementation block of the corresponding class. The extension example is shown below:
Header file ( "classname.h")
@interface ClassName ()
- (int) extensionFunction;
@end

implementation file ("classname.m")
@implementation classname

... class methods implementation

- (int) extensionFunction {
return 1;
}

@end

Jonathan

No comments:

Post a Comment