Difference between Category and Class Extension?

后端 未结 9 632
离开以前
离开以前 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 07:56

    1. Category is a way to add methods to a class whether or not source code is available, meaning you can add category to foundation classes like NSString and also to your own custom classes.

      Extension can only be added to the classes whose source code is available because compiler compiles the source code and extension at the same time.

    2. We can add extra instance variables and properties in class extension but not in category.

    3. Any variable and method inside the extension is not even accessible to inherited classes.

    4. Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.

    5. Use category when you have to break your same class code into different source files according to different functionalities, and extension when you just need to add some required methods to existing class outside the main interface file. Also, when you need to modify a publicly declared instance variable in a class, for example, readonly to readwrite, you can re-declare it in extension.

提交回复
热议问题