In Objective-c, there are two ways to extend a class to another method: category and inheritance.
1. Inheriting inherit
This is an attribute of the object-oriented language, and subclasses inherit the methods and properties of the parent class.
You cannot use categories for the following cases, you must use inheritance.
- The newly extended method has the same name as the original method, but it also requires the implementation of the parent class. Because a category is used, the implementation of the original class is overwritten and the original method cannot be accessed.
- Extended class properties, this category cannot be done.
Example code:
// ViewControllerEx.h@interface viewcontrollerex:uiviewcontroller// The method you need to add @end// viewcontrollerex.m@implementation Implementation of the Viewcontrollerex// method @end
2 category
This is a feature of the Objective-c language, which can extend the method of the class without changing the class name and the implementation of the original class. Category cannot be used to add an instance variable to an extended class.
Example code:
// There is an established rule that when a category file is named, it is the original class name + the extended identity name // nsstring+ex.h@interface nsstring (ex)// Extended Class-back method @end // nsstring+ex.m@implementation nsstring (ex)// method implementation @end
3, the following two ways to use the last category.
- For some of the classes provided by the system, such as the Nsstring,nsarray,nsnumber class, the system itself does not advocate the use of inheritance to extend the method, because the internal implementations of these classes have limitations on inheritance, so the last use of the class to extend the method.
- Categories allow developers to group related methods into separate files for classes they build, for large and complex classes, which helps to improve maintainability and simplifies the management of individual source files.
IOS syntax-category and inheritance