Usage of category in Objective-C

When the methods and implementation of a class are too bloated or you want to add more methods of the original class, you can create one or more category files according to actual needs. The purpose is to facilitate the management and maintenance of the code, and to add new methods to the existing class. Class extension method.

How to create category:

Create a new file in Xcode, select Object-C file, select category for file type, select the category of the class you want to write for Class, and then click Create.

After creation, the following syntax style is displayed:

@interface NSObject (test)

@end

Limitations of category:

1. Category can only add methods, not attributes. All p@property attributes declared in the category will not be automatically generated and implemented.

2. In the implementation of classification, the private properties of this class cannot be accessed, but they can be operated through the geter and setter methods.

3. When a method with the same name as this class appears in the classification, the method of this class will be called in a limited manner. When multiple categories have the same method, the system defaults to calling the method in the last compiled category.

category usage scenarios

1. When a class has many methods and the code is bloated, you can use classification to write methods with similar functions in the same classification to facilitate management and maintenance.

2. Expand methods for existing classes.

3. When using category classification, you need to #import the category header file.

The difference between category and inheritance:

There is no newly created class in category, and the methods in category are still called and used by objects of this class.

Inheritance is to create a new subclass, and inheritance can not only add its own methods, but also add attributes.

Guess you like

Origin blog.csdn.net/JustinZYP/article/details/124170660