OC development-the basic application of classification (31)

I. Overview

  • Classification in OC: You can extend some methods to a certain class without modifying the original code;
  • No category can be added in OC classification
  • When the OC classification and the class have a common method, the method in the OC classification will be preferentially used
  • Multiple OC classifications contain the same method. When compiling, the methods in the subsequent classifications will be called

The class to be classified (Person)

//Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
    int _age;
}
-(void)test;
@end
//Person.m
#import "Person.h"
@implementation Person
-(void)test
{
    NSLog(@"调用了test方法");
}
@end

Three Person classification

3.1 Person+MJ

//Person.MJ.h
#import "Person.h"
@interface Person (MJ)
-(void)study;
@end
//Person+MJ.m
#import "Person+MJ.h"

@implementation Person (MJ)
- (void)study
{
    NSLog(@"学习了——");
}
-(void)test
{
    NSLog(@"Person+MJ.h调用了test方法");
}
@end

3.2 Person+JJ

//Person+JJ.h
#import "Person.h"
@interface Person (JJ)
-(void)test2;
@end
//Person.JJ.m
#import "Person+JJ.h"

@implementation Person (JJ)
-(void)test2
{
    NSLog(@"test2----");
}
-(void)test
{
    NSLog(@"Person+JJ.h---test");
}
@end

Four adjust the compilation order

Five categories

5.1 Benefits

  • A huge class can be developed in modules
  • A huge class can be written by multiple people, which is more conducive to teamwork

5.2 Notes

  • Category can access instance variables of the initial class, but cannot add variables, only methods. If you want to add variables, you can consider creating subclasses through inheritance
  • Category can implement the methods of the original class, but it is not recommended because it directly replaces the original method. The consequence of this is that the original method can no longer be accessed
  • If the same method is implemented in multiple categories, only the last one involved in compilation will be effective
Published 362 original articles · 118 praises · 530,000 views

Guess you like

Origin blog.csdn.net/Calvin_zhou/article/details/105422903