OC-类的加载和初始化

from : http://www.cnblogs.com/wendingding/p/3709569.html

//
//  Person.h
//  WDDClassTest
//
//  Created by LiuChanghong on 15/9/25.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject


@end
Person.h
//
//  Person.m
//  WDDClassTest
//
//  Created by LiuChanghong on 15/9/25.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Person.h"

@implementation Person

//重写+load和+initialize方法

+(void)load{
    NSLog(@"Person +load");
}

+(void)initialize{
    NSLog(@"Person +initialize");
}

@end
Person.m
//
//  Student.h
//  WDDClassTest
//
//  Created by LiuChanghong on 15/9/25.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Person.h"

@interface Student : Person

@end
Student.h
//
//  Student.m
//  WDDClassTest
//
//  Created by LiuChanghong on 15/9/25.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Student.h"

@implementation Student

//重写+load和+initialize方法

+(void)load{
    NSLog(@"Student +load");
}

+(void)initialize{
    NSLog(@"Student +initialize");
}
@end
Student.m
//
//  main.m
//  WDDClassTest
//
//  Created by LiuChanghong on 15/9/25.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
/*
 1.当程序启动时,就会加载项目中所有的类和分类,而且加载后会调用每个类和分类的+load方法,只会调用一次;
 
 2.当第一次使用某个类时,就会调用当前类的+initialize方法,仅第一次;
 
 3.先加载父类,再加载子类(先调用父类的+load方法,再调用子类的+load方法,最后调用分类的+load方法),先初始化父类,再初始化子类(先调用父类的+initialize方法,再调用子类的+initialize方法)。
 
 4.注意:在初始化的时候,如果在分类中重写了+initialize方法,则会覆盖掉父类的。
 
 5.重写+initialize方法可以监听类的使用情况。
 */
        
        Person *person1 = [Person new];
        Person *person2 = [Person new];
        Person *person3 = [Person new];
        
        Student *student1 = [Student new];
        Student *student2 = [Student new];
        Student *student3 = [Student new];

        
    }
    return 0;
}
测试程序

输出结果

原文地址:https://www.cnblogs.com/liuchanghong/p/4839112.html