views:

81

answers:

3

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

@interface NXSMLNode (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?

+4  A: 

It's available in subclasses!

Yuji
+2  A: 

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;
bbum
A: 

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
itsaboutcode