代码之家  ›  专栏  ›  技术社区  ›  Paul

目标C类

  •  4
  • Paul  · 技术社区  · 15 年前

    如果我向类(如nsxmlnode)添加一个category方法:

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

    在nsxmlnode的子类(如nsxmlement和nsxmldocument)中,是否也可以使用此类别方法?或者,我是否必须在每个类中定义和实现方法作为一个类别,从而导致代码重复?

    3 回复  |  直到 12 年前
        1
  •  4
  •   Yuji    15 年前

    它在子类中可用!

        2
  •  2
  •   bbum    15 年前

    它将在子类中可用,如Yuji所说。

    但是,您应该给方法加前缀,这样就不会有与任何方法(公共或私有)冲突的风险。

    即。:

    -(void) mycat_myMethod;
    
        3
  •  1
  •   itsaboutcode    15 年前

    是的,它是可用的,不过我还是按代码检查一下,这里是:

    #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;
    }
    

    输出为:

    Another Method
    
    推荐文章