Question

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?

Was it helpful?

Solution

It's available in subclasses!

OTHER TIPS

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;

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top