OC basics: Class extension. Protocol
// When designing another class, some methods need to be made public (Interface), and some are for internal use only.
Class Extension: Add new features (attributes) or methods to the class.
For known classes:
1. Add directly
2. inherit (add instance variables and methods to its subclass)
3. Use extension (extensions to private methods and private properties (the methods not stated in. h are private methods ))
// Extension
// Generally, we write the class extension directly in the class. m file.
// Extension extends private methods and private attributes (methods not declared in. h)
// Expand the private Method for known classes and select Objective-C file
// Introduce the header file for use. You can add instance variables of the class to the class extension.
For unknown classes:
Category, class name, adding methods for classes without source code, cannot add instance variables
Conclusion: extension and category
1. extension adds private attributes and private methods for known classes. category is the method for adding classes without source code (unknown classes.
2. You can add instance variables (attributes) to extension, but not instance variables to category.
3. The extension file can be a. h file. category generates a pair of. h and. m files at the same time.
4. extension generally does not write code, which is written in the. m file of the class.
Summary: category and subclass (subclass)
1. category can only add methods for classes. subclass can add methods for classes and instance variables.
2. The newly added method of category becomes a part of the class and can inherit from the quilt class. The new method of subclass is available only to the subclass, and the parent class does not
3. category uses the instance (-) of the original class or the calling method (+) of the original class. subclass can be used only by the subclass.
------------------------------------- Protocol -----------------------------------------
You can become a proxy as long as you comply with the agreement.
Proxy: Do what you don't want. Others act as proxies.
If a class wants to abide by an agreement, add <protocol name> directly to the parent class in the. h file and write the required methods and optional methods to comply with the Protocol.
For example:
@ Protocol BoyfriendProtocol
@ Required // required Method
-(Void) makeMoney;
@ Optional // optional implementation
-(Void) cook; // cook
-(Void) clean; // clean
-(Void) funny; // humorous
@ End