美文网首页
对象的创建之 alloc&init

对象的创建之 alloc&init

作者: iOS小飞羊 | 来源:发表于2020-03-07 15:21 被阅读0次

让我们先看下面的代码

RFPerson *p1 = [RFPerson alloc];
RFPerson *p2 = [p1 init];
RFPerson *p3 = [p1 init];
RFNSLog(@"�%@ - %p",p1,&p1);
RFNSLog(@"�%@ - %p",p2,&p2);
RFNSLog(@"�%@ - %p",p2,&p3);
 打印结果:
2020-01-21 10:22:57.059882+0800 001-alloc&init探索[3087:71350] RF_debug: alloc 探索
�<RFPerson: 0x6000019dfb30> - 0x7ffee0895128
�<RFPerson: 0x6000019dfb30> - 0x7ffee0895120
�<RFPerson: 0x6000019dfb30> - 0x7ffee0895118

可以看到在RFPerson *p1 = [RFPerson alloc];在程序运行这句后,对象p1已经被创建了;
在说明对象创建之前这里先介绍三种代码调试的技巧

alloc流程

1.
+ (instancetype)alloc OBJC_SWIFT_UNAVAILABLE("use object initializers instead");

2.
+ (id)alloc {
    return _objc_rootAlloc(self);
}

3.
id _objc_rootAlloc(Class cls) {
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}

4.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
    if (slowpath(checkNil && !cls)) return nil;

#if __OBJC2__
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        // No alloc/allocWithZone implementation. Go straight to the allocator.
        // fixme store hasCustomAWZ in the non-meta class and 
        // add it to canAllocFast's summary
        if (fastpath(cls->canAllocFast())) {
            // No ctors, raw isa, etc. Go straight to the metal.
            bool dtor = cls->hasCxxDtor();
            /********** calloc()中申请内存*/
            id obj = (id)calloc(1, cls->bits.fastInstanceSize());
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            /*********initInstanceIsa(),将申请的内存和类建立起指示关系isa*/
            obj->initInstanceIsa(cls, dtor);
            return obj;
        }
        else {
            // Has ctor or raw isa or something. Use the slower path.
            id obj = class_createInstance(cls, 0);
            if (slowpath(!obj)) return callBadAllocHandler(cls);
            return obj;
        }
    }
#endif

    // No shortcuts available.
    if (allocWithZone) return [cls allocWithZone:nil];
    return [cls alloc];
}

所以alloc主要做了两件事:

  • 申请内存空间
  • 将申请的内存和类建立起指示关系isa

对象需要的空间

实例对象要计算它的空间,就相当于计算其属性、成员变量的空大小

//LGPerson是个继承NSObject,且没有任何属性
@interface LGPerson : NSObject
@end
//NSObject
@interface NSObject <NSObject> {
    Class isa  OBJC_ISA_AVAILABILITY;
}

Person类继承自NSObject,而NSObject本身就拥有一个 Class isa成员变量,而这个isa是个对象,所以isa占用8字节,所以意味着Person类的对象至少要开辟8字节。

1.指针,对象,结构体 大小为8字节
2.函数不占用实例对象的空间

字节对齐
#ifdef __LP64__
#   define WORD_SHIFT 3UL
#   define WORD_MASK 7UL //在arm64架构中是一个常数7
#   define WORD_BITS 64
#else
#   define WORD_SHIFT 2UL
#   define WORD_MASK 3UL
#   define WORD_BITS 32
#endif
/////////////////////////////////////////////////////
static inline uint32_t word_align(uint32_t x) {
    // 7+8 = 15
    // 0000 1111
    // 0000 1000
    //&
    // 1111 1000 ~7
    // 0000 1000 8

    // 0000 0111
    //
    // x + 7
    // 8
    // 8 二阶
    // 拓展 >> 3 << 3右移左移和(x + 7)功能一样

    return (x + WORD_MASK) & ~WORD_MASK; //这段代码的作用就是返回出去的字节大小一定是8的倍数(升对齐)
}

instanceSize(size_t extraBytes)
// Class's ivar size rounded up to a pointer-size boundary.
uint32_t alignedInstanceSize() {
        return word_align(unalignedInstanceSize());
}

size_t instanceSize(size_t extraBytes) {
        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        if (size < 16) size = 16;
        return size;
}
这个方法中,判断size是在字节对齐后是否小于16,如果小于16,就返回16

综上所诉
  • 对象最少需要内存空间 8的倍数 - 8字节对齐
  • 最少16字节
对象内存段读取
@interface LGTeacher : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) long height;
@property (nonatomic, strong) NSString *hobby;
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        LGTeacher  *p = [LGTeacher alloc];
        p.name = @"lala";
        p.age  = 18;
        p.height = 185;
        p.hobby  = @"女";
        NSLog(@"%@",p);
    }
    return 0;
}

上述代码,在NSLog处打断点进行LLDB调试

(lldb) x p //以16进制打印p对象内存地址空间
0x101d16700: 0d 14 00 00 01 80 1d 00 12 00 00 00 00 00 00 00  ................ 
0x101d16710: 50 10 00 00 01 00 00 00 b9 00 00 00 00 00 00 00  P...............
po 0x101d16700//
<LGTeacher: 0x101d16700>
(lldb) po 0x1d80010000140d//前八位就是isa。而又因为iOS是小端模式
8303516107936781//讲道理不应该是isa?因为还缺少蒙版MASK操作
(lldb) x/4xg p //以16进制打印p对象内存地址空间,打印4段
0x101d16700: 0x001d80010000140d 0x0000000000000012
0x101d16710: 0x0000000100001050 0x00000000000000b9
(lldb) po 0x001d80010000140d
8303516107936781//isa(未做蒙版mask处理)
(lldb) po 0x0000000000000012
18//age
(lldb) po 0x0000000100001050
lala//name
(lldb) po 0x00000000000000b9
185//height
(lldb) x/5gx p
0x101d16700: 0x001d80010000140d 0x0000000000000012
0x101d16710: 0x0000000100001050 0x00000000000000b9
0x101d16720: 0x0000000100001070
(lldb) po 0x0000000100001070//hobby
女

0x101d16700 :是栈顶指针起始位置,起始位置是isa,前八位就是isa。
iOS是小端模式(自行google)

alloc流程图
image

对象创建- init

//objc源码显示
- (id)init {
    return _objc_rootInit(self);
}
id
_objc_rootInit(id obj) {
    return obj;
}

可以看到,init方法啥都没干;那有什么作用呢?
作用:工厂设计,便于子类重写

- (instancetype)init {
    if (self = [super init]) {
        //可以在init方法中,进行自定义
    }
    return self;
}

对象创建- new

+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}

new: 即 alloc + init

相关文章

  • 对象的创建之 alloc&init

    让我们先看下面的代码 可以看到在RFPerson *p1 = [RFPerson alloc];在程序运行这句后,...

  • iOS进阶-01对象的创建之 alloc&init

    对象创建- alloc 在探索前,你需要先了解底层探索准备 让我们先看下面的代码 可以看到在RFPerson *p...

  • 谈谈对象之创建对象

    前端三年,一直以来忽略了对象的重要性,导致根基不稳,容易弄混很多关系。最近刚辞职,准备面试,终于可以抽出点时间是时...

  • 面向对象之创建对象

    一,工厂模式 写法 本质:就是一个函数,通过传入函数内部需要参数,返回一个对象 优点: 封装好以后可以反复调用,解...

  • Javascript之创建对象

    javascript之创建对象 学过面向对象编程的同学一定都知道,类是对象的模板,对象是根据模板创建的。 可是Ja...

  • oc对象探索 alloc&init

    初步探索 alloc 和 init 要知道alloc 和 init 都干了什么事情 我们从内存地址和指针地址来分析...

  • JAVA设计模式【创建型模式】之【PROTOTYPE】

    前言 今天来介绍对象创建型模式之原型模式(Prototype)。 其他对象创建型模式:AbstractFactor...

  • iOS编程读书笔记之Objective-c

    iOS编程读书笔记之Objective-C 对象 使用对象创建对象Party *partyInstance = [...

  • JVM 之 对象的创建

    往往越熟悉的其实越陌生 我们刚开始学 Java 的时候,就开始用这个 new 命令。一天八百遍的 new 却不知道...

  • isa的初始化&指向分析

    在探索alloc&init一篇中,我们对alloc&init有了初步的了解,其中包括对isa的初始化,本篇我们进一...

网友评论

      本文标题:对象的创建之 alloc&init

      本文链接:https://www.haomeiwen.com/subject/viycdhtx.html