Difference between Category and Class Extension?

后端 未结 9 613
离开以前
离开以前 2020-12-02 07:41

What is the difference between a Category and a Class Extension. I believe both are used to add custom methods in existing classes. Can someone throw light on this? Examplif

相关标签:
9条回答
  • 2020-12-02 08:13
    @interface SomeClass ()
    
    
    - (void) anAdditionalMethod;
    
    
    @end
    

    I think it is not the way to declare Category. Category must have a name

    @interface SomeClass (XYZ)
    
    
    - (void) anAdditionalMethod;
    
    
    @end
    

    for example

    @interface NSMutableArray (NSMutableArrayCreation)
    
    + (id)arrayWithCapacity:(NSUInteger)numItems;
    - (id)initWithCapacity:(NSUInteger)numItems;
    
    @end
    

    Declared for NSMutableArray by Apple

    0 讨论(0)
  • 2020-12-02 08:14

    A category is a way to add methods to existing classes. They usually reside in files called "Class+CategoryName.h", like "NSView+CustomAdditions.h" (and .m, of course).

    A class extension is a category, except for 2 main differences:

    1. The category has no name. It is declared like this:

      @interface SomeClass ()
      
      
      - (void) anAdditionalMethod;
      
      @end
    2. The implementation of the extension must be in the main @implementation block of the file.

    It's quite common to see a class extension at the top of a .m file declaring more methods on the class, that are then implemented below in the main @implementation section of the class. This is a way to declare "pseudo-private" methods (pseudo-private in that they're not really private, just not externally exposed).

    0 讨论(0)
  • 2020-12-02 08:14
    1. Category

    => In Objective C, when you want to add some more functionality to a class without inheritance, you simply use category for it.

    => it comes with its own .h and .m file

    => Category uses to add new method not properties.

    1. Class Extension
    -> In Objective C, when you want to make behaviour of some property private you use class extension.
    
    -> it comes with **.h** file only.
    
    -> mainly for properties.
    

    Note: when we add a new file and select a option of objective c category shows category and "category on" not "subclass of" so it shows like

    @interface className (categoryName)
    @end
    

    -You will get two file .h and .m with file name as (className+categoryName.h and className+categoryName.m)

    and in extension case you will get

    @interface className()
    @end
    

    -You will get only one file with name as className_extensionName.h

    • In category you don't own the class but in extension you are.
    0 讨论(0)
提交回复
热议问题