码迷,mamicode.com
首页 > 其他好文 > 详细

Objective-C -类的本质

时间:2015-04-20 11:18:56      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:objective   load   initialization   类的本质   

类的本质

#import "Person.h"
#import "Student.h"
#import "GoodStudent.h"
/*
 1.当程序启动时,就会加载项目中所有的类和分类,而且加载后会调用每个类和分类的+load方法。只会调用一次。

 2.当第一次使用某个类时,就会调用当前类的+initialize方法

 3.先加载父类,再加载子类(先调用父类的+load方法,再调用子类的+load方法)
   先初始化父类,再初始化子类(先调用父类的+initialize方法,再调用子类的+initialize方法)
 */

int main()
{
    // [[GoodStudent alloc] init];

    return 0;
}

void test1()
{
    Person *p = [[Person alloc] init];

    //[Person test];

    // 内存中的类对象
    // 类对象 == 类
    Class c = [p class];
    [c test];

    Person *p2 = [[c new] init];


    NSLog(@"00000");
}

void test()
{
    // 利用Person这个类创建了2个Person类型的对象
    Person *p = [[Person alloc] init];

    Person *p2 = [[Person alloc] init];

    Person *p3 = [[Person alloc] init];

    // 获取内存中的类对象
    Class c = [p class];

    Class c2 = [p2 class];

    // 获取内存中的类对象
    Class c3 = [Person class];


    NSLog(@"c=%p, c2=%p, c3=%p", c, c2, c3);

    //  类本身也是一个对象,是个Class类型的对象,简称类对象

    /*
     利用Class 创建  Person类对象

     利用 Person类对象 创建 Person类型的对象

     */
}
@interface Person : NSObject
@property int age;

+ (void)test;

@end
@implementation Person
+ (void)test
{
    NSLog(@"调用了test方法");
}


// 当程序启动的时候,就会加载一次项目中所有的类。类加载完毕后就会调用+load方法
+ (void)load
{
    NSLog(@"Person---load");
}

// 当第一次使用这个类的时候,就会调用一次+initialize方法
+ (void)initialize
{
    NSLog(@"Person-initialize");
}

@end
@interface Student : Person

@end
#import "Student.h"

@implementation Student

// 在类被加载的时候调用
+ (void)load
{
    NSLog(@"Student---load");
}


+ (void)initialize
{
    NSLog(@"Student-initialize");
}


@end
#import "Student.h"

@interface GoodStudent : Student

@end
#import "GoodStudent.h"

@implementation GoodStudent
+ (void)load
{
    NSLog(@"GoodStudent---load");
}


+ (void)initialize
{
    NSLog(@"GoodStudent-initialize");
}

@end
#import "Person.h"

@interface Person (CC)

@end
#import "Person+MJ.h"

@implementation Person (CC)
+ (void)load
{
    NSLog(@"Person(CC)---load");
}
+ (void)initialize
{
    NSLog(@"Person(CC)-initialize");
}
@end

Objective-C -类的本质

标签:objective   load   initialization   类的本质   

原文地址:http://blog.csdn.net/wangzi11322/article/details/45146343

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!