Classification (Category)

  • Declare the category in the.h file

    • 1) New methods must be written between @interface and @end

    • 2)ClassName the ClassName of the existing class (for which class to extend the method)

    • 3)CategoryName CategoryName to be declared

    • 4)NewMethod NewMethod

      @interface ClassName (CategoryName)
      NewMethod; // Add a method to the category
      // Adding variables to categories is not allowed
      @end
      Copy the code

Note: 1) Classification can only add methods, not member variables

2) Writing property in a class only generates getter/setter method declarations

3) Classes can access member variables in the original class

4) If there is a method with the same name as the original class, the method in the classification will be called first, and the method in the original class will be ignored

  • Priority of method calls (from highest to lowest)

    • Classification (the last category involved in compilation is preferred)
    • The original class
    • The parent class

5) Execute the last compiled file method if there is a method with the same name in more than one class (don't do this in development)

  • Implement categories in.m files:

    • 1) The implementation of the new method must be between the @implementation and the @end
    • 2)ClassName indicates the ClassName of the existing class
    • 3)CategoryName CategoryName to be declared
    • 4)NewMethod The implementation of the newly added method
@implementation ClassName(CategoryName)NewMethod ... .@end
Copy the code

Class Extension

  • Extension categories are also called Extendsion, and Extension is a special case of Category

  • You can extend private member variables and methods for a class

    • I'll write it in my dot m file
@interfaceThe name of the class ()
@end
Copy the code
  • By contrast, there is no category name, so some people call it “anonymous category.”

  • using

#import "NSString+NJ.h"

@implementation NSString (NJ)- (int)count{
    int number=0;

    for (int i= 0; i< self.length; ++i) {
    //self in the object method is the object on which the method is currently called
        unichar c=[self characterAtIndex:i];
        if(c>='0'&& c<='0'); number ++; }}@end

//main.m
NSString *str=@"fds64jkl43fjdslkf";
int count =[NSString countWithStr:str];
Copy the code