OC development-the nature of class (33)

I. Overview

  • The class is also an object, which is an object of type Class, referred to as "class object" for short
  • Class type definition typedef struct objc_clas *Class
  • The class name represents the class object, each class has only one class object

Relationship between two types

2.1 Person

//Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property int age;
+(void)test;
@end
//Person.m
#import "Person.h"
@implementation Person
+(void)test
{
    NSLog(@"Person调用了test++++++");
}
+ (void)load
{
    NSLog(@"Person----load");
}
+(void)initialize
{
    NSLog(@"Person---initialize");
}
@end

2.2 Student class (subclass of Person)

//Student.h
#import "Person.h"
@interface Student : Person
@end
//Student.m
#import "Student.h"
@implementation Student
+(void)load
{
    NSLog(@"Student---load");
}
+(void)initialize
{
    NSLog(@"Student---initialize");
}
@end

2.3 GoogStudent class (subclass of Student)

//GoodStudent.h
#import "Student.h"
@interface GoodStudent : Student
@end
//GoodStudent.m
#import "GoodStudent.h"
@implementation GoodStudent
+(void)load
{
    NSLog(@"GoodStudent---load");
}
+(void)initialize
{
    NSLog(@"GoodStudent---initialize");
}
@end

2.4 Person (MJ) category (Person classification)

//Person+MJ.h
#import "Person.h"
@interface Person (MJ)
@end
//Person+MJ.m
#import "Person+MJ.h"
@implementation Person (MJ)
+(void)load
{
 NSLog(@"Person(MJ)---load");
}
+(void)initialize
{
    NSLog(@"Person(MJ)---initialize");
}
@end

Three types of essence

3.1 Class

 Person *p1=[[Person alloc]init];
 Person *p2=[[Person alloc]init];
 Person *p3=[[Person alloc]init];
         
 Class c1=[p1 class];
 Class c2=[p2 class];
 Class c3=[Person class];
 NSLog(@"c1=%p,c2=%p,c3=%p",c1,c2,c3);

3.2 Class initialization (load, initialize)

Person *p=[[Person alloc]init];
Class c=[p class];
       
[Person test];
[c test];
       
 Person *p2=[[c new]init];
 NSLog(@"Person ---%d",p2.age);

Four + load and + initialize

4.1 +load

  • All classes and categories are loaded when the program starts, and the + load method of all classes and categories is called
  • Load the parent class first, then load the subclass: that is, first call + load of the parent class, and then call + load of the subclass
  • Load the original meta-class first, and then load the category
  • Regardless of whether this class is useful when the program is running, + load will be called to load

4.2 +initialize

  • When you first use a class (such as creating an object, etc.), the + initialize method will be called once
  • A class will only call the + initialize method once, first call the parent class, then call the subclass

4.3 2 ways to get class objects

//方式一
Class c=[Person class];//类方法
方式二
Person *p=[Person new];
Class c2=[p class];//对象方法
Published 362 original articles · 118 praises · 530,000 views

Guess you like

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