咱們平時常常會寫下這樣的代碼:bash
NSObject *obj1 = [[NSObject alloc] init];
NSObject *obj2 = [NSObject new];
複製代碼
那麼alloc和init還有new,到底是怎麼建立對象和初始化對象的呢???
注:本文分析基於objc4-750源碼進行的。架構
下面咱們就來看下alloc和init的源碼,來分析對象的建立過程:app
+ (id)alloc {
return _objc_rootAlloc(self);
}
複製代碼
當調用alloc的時候,會繼續調用_objc_rootAlloc
函數,下面看下_objc_rootAlloc
函數的實現:ide
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
複製代碼
_objc_rootAlloc
函數會繼續調用callAlloc
函數,咱們看下callAlloc
實現:函數
static ALWAYS_INLINE id callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
if (slowpath(checkNil && !cls)) return nil;
#if __OBJC2__
//1.判斷是否有自定義allocWithZone,沒有的話,調用下面的方法。
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
// 1.1查看一下類是否能快速分配內存
if (fastpath(cls->canAllocFast())) {
//1.1.1 是否有析構函數
bool dtor = cls->hasCxxDtor();
//1.1.2 分配內存
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
//1.1.3是否分配成功
if (slowpath(!obj)) return callBadAllocHandler(cls);
//1.1.4 初始化isa指針
obj->initInstanceIsa(cls, dtor);
return obj;
}
else {
// 1.2.1分配內存
id obj = class_createInstance(cls, 0);
//1.2.2是否分配成功
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
}
}
#endif
//2. 若是allocWithZone使用 allocWithZone分配內存
if (allocWithZone) return [cls allocWithZone:nil];
//3.繼續調用alloc
return [cls alloc];
}
複製代碼
關於fastpath和slowpath學習
因此fastpath的含義是,爲1的機率大,slowpath的含義是爲0的機率大。是爲了優化編譯器使用的。
複製代碼
總結callAlloc
函數的過程以下:
1.若是沒有自定義allocWithZone。優化
fastpath(!cls->ISA()->hasCustomAWZ()
🔽
bool hasCustomAWZ() {
return ! bits.hasDefaultAWZ();
}
🔽
bool hasDefaultAWZ() {
return data()->flags & RW_HAS_DEFAULT_AWZ;
}
🔽
#define RW_HAS_DEFAULT_AWZ (1<<16)
複製代碼
這裏是經過判斷class_rw_t* data()中的flags中的值的第16位
,來判斷是重寫了allocWithZone。關於class_rw_t和flags我會在其它文章解釋。ui
1.1若是能快速分配內存atom
fastpath(cls->canAllocFast())
🔽
bool canAllocFast() {
assert(!isFuture());
return bits.canAllocFast();
}
🔽
#if FAST_ALLOC
bool canAllocFast() {
return bits & FAST_ALLOC;
}
#else
bool canAllocFast() {
return false;
}
#endif
🔽
#define FAST_ALLOC (1UL<<2)
複製代碼
可否快速分配內存,是根據cls->bits->FAST_ALLOC來判斷的,最終是經過
bits中的第二位來判斷是否能快速分配內存。
1.1.2 分配內存spa
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
複製代碼
這裏是經過calloc函數和 cls->bits.fastInstanceSize()分配的內存的。calloc函數是分配加初始化一塊兒進行的。
C語言跟內存申請相關的函數主要有 alloca、calloc、malloc、realloc等.
1)alloca是向棧申請內存,所以無需釋放.
2)malloc分配的內存是位於堆中的,而且沒有初始化內存的內容,所以基本上malloc以後,調用函數memset來初始化這部分的內存空間.
3)calloc則將初始化這部分的內存,設置爲0.
4)realloc則對malloc申請的內存進行大小的調整.
1.1.3 是否分配成功
if (slowpath(!obj)) return callBadAllocHandler(cls);
複製代碼
1.1.4 初始化isa指針
obj->initInstanceIsa(cls, dtor);
🔽
inline void objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
initIsa(cls, true, hasCxxDtor);
}
🔽
inline void objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
{
assert(!isTaggedPointer());
if (!nonpointer) {
isa.cls = cls;
} else {
assert(!DisableNonpointerIsa);
assert(!cls->instancesRequireRawIsa());
isa_t newisa(0);
newisa.bits = ISA_MAGIC_VALUE;
newisa.has_cxx_dtor = hasCxxDtor;
newisa.shiftcls = (uintptr_t)cls >> 3;
isa = newisa;
}
}
複製代碼
這裏重點看下說下isa的初始化,從上面能夠看到isa初始化主要是bits、has_cxx_dtor、shiftcls這三個字段,那麼這三個字段是什麼呢
bits一共64位,包含類指針、是否有關聯對象,析構函數等等,下面是arm64和x86_64架構下bits的含義
# if __arm64__
# define ISA_MASK 0x0000000ffffffff8ULL
# define ISA_MAGIC_MASK 0x000003f000000001ULL
# define ISA_MAGIC_VALUE 0x000001a000000001ULL
struct {
uintptr_t indexed : 1;
uintptr_t has_assoc : 1;
uintptr_t has_cxx_dtor : 1;
uintptr_t shiftcls : 33; // MACH_VM_MAX_ADDRESS 0x1000000000
uintptr_t magic : 6;
uintptr_t weakly_referenced : 1;
uintptr_t deallocating : 1;
uintptr_t has_sidetable_rc : 1;
uintptr_t extra_rc : 19;
# define RC_ONE (1ULL<<45)
# define RC_HALF (1ULL<<18)
};
# elif __x86_64__
# define ISA_MASK 0x00007ffffffffff8ULL
# define ISA_MAGIC_MASK 0x001f800000000001ULL
# define ISA_MAGIC_VALUE 0x001d800000000001ULL
struct {
uintptr_t indexed : 1;
uintptr_t has_assoc : 1;
uintptr_t has_cxx_dtor : 1;
uintptr_t shiftcls : 44; // MACH_VM_MAX_ADDRESS 0x7fffffe00000
uintptr_t magic : 6;
uintptr_t weakly_referenced : 1;
uintptr_t deallocating : 1;
uintptr_t has_sidetable_rc : 1;
uintptr_t extra_rc : 8;
# define RC_ONE (1ULL<<56)
# define RC_HALF (1ULL<<7)
};
複製代碼
arm64下 ISA_MAGIC_VALUE對應的二進制是11010000000000000000000000000000000000001,結構以下圖:
has_cxx_dtor
表示該對象是否有 C++ 或者 Objc 的析構器
shiftcls
類的指針。arm64架構中有33位能夠存儲類指針。
源碼中isa.shiftcls = (uintptr_t)cls >> 3;
將當前地址右移三位的主要緣由是用於將 Class 指針中無用的後三位清除減少內存的消耗,由於類的指針要按照字節(8 bits)對齊內存,其指針後三位都是沒有意義的 0。
這就是ISA指針的初始化內容,暫且先了解這麼多。
1.2 若是不能快速分配內存
1.2.1分配內存
若是不能快速分配內存,使用class_createInstance
來分配內存
id obj = class_createInstance(cls, 0);
🔽
id class_createInstance(Class cls, size_t extraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
🔽
id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
if (!cls) return nil;
assert(cls->isRealized());
// Read class's info bits all at once for performance bool hasCxxCtor = cls->hasCxxCtor(); bool hasCxxDtor = cls->hasCxxDtor(); bool fast = cls->canAllocNonpointer(); size_t size = cls->instanceSize(extraBytes); if (outAllocatedSize) *outAllocatedSize = size; id obj; if (!zone && fast) { obj = (id)calloc(1, size); if (!obj) return nil; obj->initInstanceIsa(cls, hasCxxDtor); } else { if (zone) { obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size); } else { obj = (id)calloc(1, size); } if (!obj) return nil; obj->initIsa(cls); } if (cxxConstruct && hasCxxCtor) { obj = _objc_constructOrFree(obj, cls); } return obj; } 複製代碼
咱們看到這裏面zone爲nil,最終也是經過calloc來分配內存,以後初始化isa指針,若是有構造函數,調用構造函數。
1.2.2是否分配成功
if (slowpath(!obj)) return callBadAllocHandler(cls);
複製代碼
2. 若是allocWithZone爲True ,使用 allocWithZone分配內存
if (allocWithZone) return [cls allocWithZone:nil];
複製代碼
3.繼續調用alloc進行內存分配
return [cls alloc];
複製代碼
以上就是這就是alloc的整個過程,總結爲三步:
1.若是沒有自定義allocWithZone
2. 若是allocWithZone爲True ,使用 allocWithZone分配內存
3. 繼續調用alloc進行內存分配
下面咱們看下init的代碼實現:
- (id)init {
return _objc_rootInit(self);
}
🔽
id _objc_rootInit(id obj)
{
return obj;
}
複製代碼
從上面代碼能夠看出,init只是返回了對象自己。並無初始化對象,其實這裏的初始化操做已經在alloc中作了,這裏跟咱們認爲的alloc負責內存分配,init負責初始化的仍是挺不同的。
因而我又作了實驗:
TestObject.h
@interface TestObject : NSObject
@property(nonatomic, assign) NSInteger num;
@property(nonatomic, strong) NSObject *obj;
@end
main.m
TestObject *obj = [TestObject alloc];
NSLog(@"TestObject.num=%ld",(long)obj.num);
NSLog(@"TestObject.obj=%@",obj.obj);
複製代碼
結果:
2019-08-04 14:31:13.294387+0800 objc-debug[5002:2825779] TestObject.num=0
2019-08-04 14:31:13.294401+0800 objc-debug[5002:2825779] TestObject.obj=(null)
複製代碼
因此,之後咱們建立對象的時候,是否是能夠不寫init了???
因而我又查看了以前的objc源碼,較早包含NSObject.mm版本是objc4-532,裏面的init也只是返回self。那麼若是是直接繼承自NSObject,而且沒有重寫init方法的類,能夠不寫init,直接使用alloc,可是像NSString、NSArray這種,就不能不調用init方法,會報錯,會要調用init。
咱們能夠看到new的實現,實際上是和alloc調用的同一個函數callAlloc
,因此能夠說[NSObject new]和[[NSObject alloc] init]是等價的,源碼以下:
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
複製代碼
首先咱們看下這個實例:
TestObject.h
@interface TestObject : NSObject
@property(nonatomic, assign) long num;
@property(nonatomic, assign) int num1;
@property(nonatomic, assign) long num2;
@property(nonatomic, strong) NSObject *obj;
@end
main.m
int main(int argc, const char * argv[]) {
@autoreleasepool {
TestObject *obj = [TestObject new];
NSLog(@"InstanceSize:%zd",class_getInstanceSize([obj class]));
NSLog(@"ClassSize:%zd",malloc_size((__bridge const void *)obj));
NSObject *obj1 = [NSObject new];
NSLog(@"InstanceSize:%zd",class_getInstanceSize([obj1 class]));
NSLog(@"ClassSize:%zd",malloc_size((__bridge const void *)obj1));
}
return 0;
}
複製代碼
arm64下打印結果是:
TestObject:
InstanceSize:40
ClassSize:48
NSObject:
InstanceSize:8
ClassSize:16
複製代碼
下面咱們來分析下打印結果:
咱們先分析下NSObject對象:
struct NSObject_IMPL{
class isa
}
複製代碼
由於NSObject只含有一個isa指針,多有實例變量的內存是8字節。那ClassSize爲何是16呢?
不論是使用new仍是alloc,底層都是用callAlloc來給對象分配內存的,下面咱們看下callAlloc的部分源碼:
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
...
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
...
}
複製代碼
這裏是使用class_createInstance分配內存的,接下來看其源碼:
id class_createInstance(Class cls, size_t extraBytes)
{
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
static __attribute__((always_inline)) id _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
if (!cls) return nil;
assert(cls->isRealized());
// Read class's info bits all at once for performance bool hasCxxCtor = cls->hasCxxCtor(); bool hasCxxDtor = cls->hasCxxDtor(); bool fast = cls->canAllocNonpointer(); size_t size = cls->instanceSize(extraBytes); if (outAllocatedSize) *outAllocatedSize = size; id obj; if (!zone && fast) { obj = (id)calloc(1, size); if (!obj) return nil; obj->initInstanceIsa(cls, hasCxxDtor); } else { if (zone) { obj = (id)malloc_zone_calloc ((malloc_zone_t *)zone, 1, size); } else { obj = (id)calloc(1, size); } if (!obj) return nil; // Use raw pointer isa on the assumption that they might be // doing something weird with the zone or RR. obj->initIsa(cls); } if (cxxConstruct && hasCxxCtor) { obj = _objc_constructOrFree(obj, cls); } return obj; } 複製代碼
咱們在_class_createInstanceFromZone中看到很是重要的一句,size_t size = cls->instanceSize(extraBytes);
也就是最後分配對象的內存大小,咱們是在instanceSize中:
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;
}
複製代碼
咱們看到這裏面再分配對象的時候,若是對象小於16個字節,也要分配16字節的,具體緣由是什麼呢?有一行註釋說明CF requires all objects be at least 16 bytes.
下面咱們再看下TestObject的內存分配,對應的結構應該是:
struct TestObject_IMPL{
class isa;//8
long _num;//8
int _num1;//4
long _num2;//8
NSObject _obj;//8
}
複製代碼
TestObjects的實例對象應該是8+8+4+8+8,一共36字節,可是實際是40,這是爲何呢,這是因內存對齊的緣由:
結構體存在一個內存對其的操做,這樣有利於CPU的訪問,結構體爲了保證內存對其 最重的真用內存必定是佔用最大的一個變量的倍數, 在這裏咱們isa佔用了8個字節數, 因此雖然實際上只使用了36個字節,可是爲了保證內存對其的規則 因此使用了40個字節.
這裏TestObjects的類對象大小是48,而不是40,這裏也是因爲內存對齊的緣由。
若是您以爲寫得不錯,請給我一個贊!