1.alloc 方法到底干了什么?
先来看一段代码
Person *p1 = [Person alloc];
Person *p2 = [p1 init];
Person *p3 = [p1 init];
NSLog(@"%@ --- %p",p1,&p1);
NSLog(@"%@ --- %p",p2,&p2);
NSLog(@"%@ --- %p",p3,&p3);
<Person: 0x10103be00> --- 0x7ffeefbff4b0
<Person: 0x10103be00> --- 0x7ffeefbff4a0
<Person: 0x10103be00> --- 0x7ffeefbff4a8
- 这里通过打印结果发现 p1, p2, p3 的内存地址是相同的说明它们指向的是同一堆区内存区域,但是指针地址不同
如图所示:
2.从 OC 源码的跟踪 alloc
从源码直接 command + click 查看 alloc 方法
+ (id)alloc {
return _objc_rootAlloc(self);
}
在 _objc_rootAlloc 方法里面调用了 callAlloc方法
id _objc_rootAlloc(Class cls) {
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
在 callAlloc方法里面调用了_class_createInstanceFromZone
// 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__
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));
}
这里面调用了_class_createInstanceFromZone方法
NEVER_INLINE
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) {
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: 初始化 isa 关联类?
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);
}
这里面主要做三件事情
1.计算需要开辟的内存空间大小 size = cls->instanceSize(extraBytes);
2.开辟内存 obj = (id)calloc(1, size);
3.实例化 isa obj->initIsa(cls);
下面是总结的alloc方法的实际流程图
3.发现问题
1.为什么一开始我们调用的 alloc 的方法,底层却调用的是 objc_alloc
这里是因为在 llvm 源码中系统在编译期间就对 alloc 方法做了替换