iOS开发之常用技术点iOS基本功Objective-C

类的本质和存储细节

2019-02-21  本文已影响25人  越天高

1.类的本质


2.如何获取类对象

格式:[实例对象   class ];
如:   [dog class];
格式:[类名 class];
如:[Dog class]

3.类对象的用法

[Dog test];

Class c = [Dog class];
[c test];
Dog *g = [Dog new];

Class c = [Dog class];
Dog *g1 = [c new];

4.类对象的存储

ldxcc.png

5.OC实例对象 类对象 元对象之间关系

NSObject.h
@interface NSObject <NSObject> {
    Class isa  OBJC_ISA_AVAILABILITY;
}
objc.h
/// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;

/// Represents an instance of a class.
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};
runtime.h
struct objc_class {
    Class isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
    Class super_class                                        OBJC2_UNAVAILABLE;
    const char *name                                         OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list *ivars                             OBJC2_UNAVAILABLE;
    struct objc_method_list **methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache *cache                                 OBJC2_UNAVAILABLE;
    struct objc_protocol_list *protocols                     OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;

类的启动过程

1.+load方法

在程序启动的时候会加载所有的类和分类,放到代码区,并调用所有类和分类的+load方法(只会调用一次)
先加载父类,再加载子类;也就是先调用父类的+load,再调用子类的+load
先加载元原始类,再加载分类
不管程序运行过程有没有用到这个类,都会调用+load加载

@implementation Person

+ (void)load
{
    NSLog(@"%s", __func__);
}
@end

@implementation Student : Person

+ (void)load
{
    NSLog(@"%s", __func__);
}
@end

输出结果:
+[Person load]
+[Student load]

2.+initialize

在第一次使用某个类时(比如创建对象等),只会调用一次+initialize方法
一个类只会调用一次+initialize方法,先调用父类的,再调用子类的
initialize方法在整个程序的运行过程中只会被调用一次, 无论你使用多少次这个类都只会调用一次
initialize用于对某一个类进行一次性的初始化

@implementation Person
+ (void)initialize
{
    NSLog(@"%s", __func__);
}
@end

@implementation Student : Person
+ (void)initialize
{
    NSLog(@"%s", __func__);
}
@end
int main(int argc, const char * argv[]) {
    Student *stu = [Student new];
    return 0;
}
输出结果:
+[Person initialize]
+[Student initialize]
上一篇下一篇

猜你喜欢

热点阅读