美文网首页
alloc init探索

alloc init探索

作者: 张墩墩 | 来源:发表于2020-09-06 20:19 被阅读0次

1、alloc init

首先用alloc生成一个LGPerson对象。在init另外的对象。

 - (void)viewDidLoad {
    [super viewDidLoad];
    LGPerson *p1 = [LGPerson alloc];
    LGPerson *p2 = [p1 init];
    LGPerson *p3 = [p2 init];
    
    NSLog(@"%@ - %p - %p",p1,p1,&p1);
    NSLog(@"%@ - %p - %p",p2,p2,&p2);
    NSLog(@"%@ - %p - %p",p3,p3,&p3);
}

输出生成的对象信息。


对象信息

从输出的对象信息来看。三个对象的指针地址不同。但是指向的却是同一块内存。
LGPerson对象alloc已经开辟内存、对象已经生成。init没有对已经生成的内存进行任何处理。

截屏2020-09-06 15.19.15.png

查找动态链接库

  • 符号断点
    alloc方法添加符号断点。
    注意:alloc方法调用较多。先定位到对象的alloc,在开启alloc的符号断点。
    截屏2020-09-06 15.32.00.png
42BE4DEE-A234-4B04-BF5D-39407E81A407.png
  • control + step into

    control + step into
    添加符号断点
  • 汇编查看

    打开汇编
    打开汇编定位到需要的对象,进入汇编会发现objc_alloc。将断点到汇编的objc_alloc地方。接下来重复control + step into 的操作。
    objc_alloc

2、alloc 开辟内存探索

动态库源码搜索需要的objc库。
2.1 alloc源码探索
根据LGPersonalloc查找跟随源码进入

  • 第一步alloc
+ (id)alloc {
    return _objc_rootAlloc(self);
}
  • 第二步_objc_rootAlloc
// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
  • 第三步callAlloc
// Call [cls alloc] or [cls allocWithZone:nil], with appropriate 
// shortcutting optimizations.
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
    /** slowpath      fastpath
     * 其作用是将最有可能执行的分支告诉编译器
     * x很可能为真, fastpath 可以简称为 真值判断
     * #define fastpath(x) (__builtin_expect(bool(x), 1))
     * x很可能为假,slowpath 可以简称为 假值判断
     * #define slowpath(x) (__builtin_expect(bool(x), 0))
     */
    if (slowpath(checkNil && !cls)) return nil;
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        return _objc_rootAllocWithZone(cls, nil);
    }
#endif

    // No shortcuts available.
    if (allocWithZone) {
        return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}

这是出现了if判断,无法确定执行哪一步。可以为相关方法设置符号断点来确定执行哪一部分。此处执行_objc_rootAllocWithZone

  • 第四步_objc_rootAllocWithZone
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}
  • 第五步_class_createInstanceFromZone
static ALWAYS_INLINE id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
                              int construct_flags = OBJECT_CONSTRUCT_NONE,
                              bool cxxConstruct = true,
                              size_t *outAllocatedSize = nil)
{
    ASSERT(cls->isRealized());

    // Read class's info bits all at once for performance
    bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();
    size_t size;
    // 1:要开辟多少内存
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {//在iOS8及以上废弃了zone,(通过zone申请)
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        // 2;怎么去申请内存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    // 3: 类Obj和内存地址指针相关联
    if (!zone && fast) {
        obj->initInstanceIsa(cls, hasCxxDtor);
    } else {
        // Use raw pointer isa on the assumption that they might be
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }

    if (fastpath(!hasCxxCtor)) {
        return obj;
    }

    construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
    return object_cxxConstructFromClass(obj, cls, construct_flags);
}

分析此处源码实现可知这里是alloc的核心实现。主要做了三件事情:

  • cls->instanceSize(extraBytes);计算需要开辟的内存空间大小
  • obj = (id)calloc(1, size);申请开辟内存空间
  • obj->initInstanceIsa(cls, hasCxxDtor);将类和开辟的内存空间地址相关联
    开辟内存空间
关联类 alloc流程

2.2 instanceSize 计算开辟内存空间大小

  • 第一步instanceSize
       size_t instanceSize(size_t extraBytes) const {
        //编译器快速计算内存大小
        if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
        }
        //计算的类中所有属性的大小 + 额外的字节数0
        size_t size = alignedInstanceSize() + extraBytes;
        // CF requires all objects be at least 16 bytes.
        if (size < 16) size = 16;
        return size;
    }

通过符号断点调试。此处执行cache.fastInstanceSize(extraBytes);

  • 第二步fastInstanceSize
size_t fastInstanceSize(size_t extra) const
    {
        ASSERT(hasFastInstanceSize(extra));

        if (__builtin_constant_p(extra) && extra == 0) {
            return _flags & FAST_CACHE_ALLOC_MASK16;
        } else {
            size_t size = _flags & FAST_CACHE_ALLOC_MASK;
            // remove the FAST_CACHE_ALLOC_DELTA16 that was added
            // by setFastInstanceSize
            return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
        }
    }
  • 第三步align1616字节对齐算法
static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}
截屏2020-09-06 19.05.44.png

现代计算机中,内存空间按照字节划分,理论上可以从任何起始地址访问任意类型的变量。但实际中在访问特定类型变量时经常在特定的内存地址访问,这就需要各种类型数据按照一定的规则在空间上排列,而不是顺序一个接一个地存放,这就是字节对齐。
一个对象中,第一个属性isa占8字节,一个对象肯定还有其他属性,当无属性时,会预留8字节,即16字节对齐,如果不预留,相当于这个对象的isa和其他对象的isa紧挨着,容易造成访问混乱访问到其他内存地址。16字节对齐后,可以加快CPU读取速度,同时使访问更安全,不会产生访问混乱的情况。

3、init探索

init 源码

+ (id)init {
    return (id)self;
}

- (id)init {
    return _objc_rootInit(self);
}

id
_objc_rootInit(id obj)
{
    // In practice, it will be hard to rely on this function.
    // Many classes do not properly chain -init calls.
    return obj;
}

init直接返回self。这里的init是一个构造方法 通过工厂设计(工厂方法模式)。主要是用于给用户提供构造方法入口。这里能使用id强转的原因,主要因为内存字节对齐后,可以使用类型强转为你所需的类型

4、new 源码探索

new 源码

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

new直接调用callAlloc,并且实现了init方法。所有new等价于[alloc init]
在开发中有时生成对象有时需要根据外部变化的条件生成对象例:

-(id)initWithCurrentAge:(int)currentAge{
    self = [super init];
    if (self) {
        self.age = currentAge;
    }
    return self;
}

此时在用new创建将不会调用构造-(id)initWithCurrentAge:(int)currentAge方法。

5、内存计算示例

  • 第一步、创建LGPerson对象,不添加任何属性。此时只有isa8个字节。LGPerson对象需要8,按照内存开辟16字节对齐原则应开辟16结果图1
LGPerson *p1 = [LGPerson alloc];
NSLog(@"objc对象需要的内存大小: %zd", class_getInstanceSize([p1 class]));
NSLog(@"objc对象分配的内存大小: %zd", malloc_size((__bridge const void *)(p1)));
结果图1
结果输出LGPerson对象需要8字节,内存分配了16
  • 第二步 LGPerson添加NSString 类型 name属性
    LGPerson对象所需 isa + name = 8 + 8 = 16,内存应开辟16结果图2
    截屏2020-09-07 19.27.21.png
@interface LGPerson : NSObject
@property (strong, nonatomic) NSString *name;
@end

LGPerson *p1 = [LGPerson alloc];
NSLog(@"objc对象需要的内存大小: %zd", class_getInstanceSize([p1 class]));
NSLog(@"objc对象分配的内存大小: %zd", malloc_size((__bridge const void *)(p1)));
结果图2
  • 第三步 添加int 类型age属性
    LGPerson对象所需isa + name + age = 8 + 8 + 4 = 20。内存应开辟32
    截屏2020-09-07 19.28.15.png
@interface LGPerson : NSObject
@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) int age;
@end

结果图3

截屏2020-09-07 18.43.20.png
结果显示内存分配确为32。但是对象需要内存确多了4
结合第二步中namename的操作可以确定是int 类型age出了问题。
通过输出确定int 类型age在此处确为4字节
int类型输出

接下来进入class_getInstanceSize源码查看,进行了什么计算

size_t class_getInstanceSize(Class cls)
{
    if (!cls) return 0;
    return cls->alignedInstanceSize();
}
uint32_t alignedInstanceSize() const {
        return word_align(unalignedInstanceSize());
    }
static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}

发现此处做了一个8字节对齐的操作。为我们int 类型预留了4字节的空间。所以LGPerson对象的内存变成了24

结果图
  • 第四步 在添加一个int 类型age1。查看一下age1是否占用了第三步int的预留空间
    结果图

结果显示LGPerson对象所需要内存没有增加。

结果图

结果显示age1确实占据了预留的空间

相关文章

  • alloc init探索

    1、alloc init 首先用alloc生成一个LGPerson对象。在init另外的对象。 输出生成的对象信息...

  • alloc & init 探索

    首先创建一个对象 p1,p2,p3 打印结果结果 那么问题来了 alloc 做了什么?init 做了什么?上面的打...

  • iOS alloc & init 探索

    0x000 从哪里入手? 先看看main函数 0x001 初探? 为什么是 alloc init? alloc i...

  • iOS alloc & init 探索

    初探 1、新建一个Person 类 先思考打印情况 再运行 得到结果为 猜测:1、init 没有对内存进行任何...

  • alloc&init探索

    OC底层原理学习 alloc 初探 首先创建一个继承于NSObject的Person类带着以下几个疑问,查看打印结...

  • alloc&init探索

    main函数的加载流程 1.在int main前面打个断点 然后增加一个_objc_init的符号断点 记得关闭左...

  • alloc与init探索

    知识点概要 引入alloc干了什么?为什么要有init?为什么要有new?直接使用有何缺陷?[NSObject a...

  • alloc&init 探索

    alloc&init 探索 首先要明确alloc做了什么,init做了什么。 上方的p1/p2/p3经打印是一模一...

  • 1.对象原理探究

    alloc 探索 alloc 已经创建了对象 init alloc 实现 原理 源码实现 介绍三种方式 1、下断点...

  • OC底层原理系列文集

    1、对象底层之alloc&init&new源码分析+三种探索方式OC底层原理01-alloc流程探索[https:...

网友评论

      本文标题:alloc init探索

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