Paul
Paul

Reputation: 2728

Objective-C Categories

If I add a category method to a class, such as NSXMLNode:

@interface NSXMLNode (mycat)
- (void)myFunc;
@end

Will this category method also be available in subclasses of NSXMLNode, such as NSXMLElement and NSXMLDocument? Or do I have to define and implement the method as a category in each class, leading to code duplication?

Upvotes: 4

Views: 633

Answers (3)

itsaboutcode
itsaboutcode

Reputation: 25099

Yes it will be available, I though of check it by code and here it is:

#import <Foundation/Foundation.h>

@interface Cat1 : NSObject {

}

@end

@implementation Cat1

- (void) simpleMethod
{

    NSLog(@"Simple Method");
}

@end


@interface Cat1 (Cat2) 
- (void) addingMoreMethods;

@end

@implementation Cat1 (Cat2)

- (void) addingMoreMethods
{

    NSLog(@"Another Method");
}

@end


@interface MYClass : Cat1

@end

@implementation MYClass


@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


    MYClass *myclass = [[MYClass alloc] init];
    [myclass addingMoreMethods];
    [myclass release];
    [pool drain];
    return 0;
}

The output is:

Another Method

Upvotes: 2

bbum
bbum

Reputation: 162712

It will be available in subclasses as Yuji said.

However, you should prefix your method such that there is no risk that it conflicts with any method, public or private.

I.e.:

-(void) mycat_myMethod;

Upvotes: 2

Yuji
Yuji

Reputation: 34185

It's available in subclasses!

Upvotes: 4

Related Questions