开发者

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 NSXMLN开发者_JAVA百科ode, 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?


It's available in subclasses!


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜