前言
Objective-C
一門面向?qū)ο蟮恼Z音.我們都知道Objective-C
創(chuàng)建對象需通過alloc
以及init
兩個消息.alloc
的作用是分配內(nèi)存,init
則是初始化對象.
MyObject *objc1 = [MyObject alloc];
MyObject *objc2 = [objc1 init];
MyObject *objc3 = [objc1 init];
NSLog(@" %@ - %p", objc1, &objc1);
NSLog(@" %@ - %p", objc2, &objc2);
NSLog(@" %@ - %p", objc3, &objc3);
//打印
<MyObject: 0x600002b21ee0> - 0x600002b21ee0 - 0x7ffee67de0e8
<MyObject: 0x600002b21ee0> - 0x600002b21ee0 - 0x7ffee67de0e0
<MyObject: 0x600002b21ee0> - 0x600002b21ee0 - 0x7ffee67de0d8
結(jié)論: 3個對象指向同一內(nèi)存空間,內(nèi)存地址是相同的,對象的指針地址是不同的
指向這個對象的指針空間由棧分配,所以可以看到椝蚜ⅲ空間從高位到低位,依次降低.
又因為64位設(shè)備,指針大小為8字節(jié),所以從 0x600002b21ee0 每次減去 0x8.
那么對象在創(chuàng)建的過程中,alloc
和init
又做了些什么呢?
準(zhǔn)備工作
alloc分析
- 進(jìn)入
alloc
方法
+ (id)alloc {
return _objc_rootAlloc(self);
}
- 進(jìn)入
_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*/);
}
- 進(jìn)入
callAlloc
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false) {
#if __OBJC2__
// checkNil 為false,!cls 也為false,不會返回nil
if (slowpath(checkNil && !cls)) return nil;
// 是否有自定義的 +allocWithZone 實現(xiàn)
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));
}
- 通過斷點調(diào)試,發(fā)現(xiàn)進(jìn)入
_objc_rootAllocWithZone
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
// allocWithZone under __OBJC2__ ignores the zone parameter
//zone 參數(shù)不再使用 類創(chuàng)建實例內(nèi)存空間
return _class_createInstanceFromZone(cls, 0, nil,
OBJECT_CONSTRUCT_CALL_BADALLOC);
}
- 進(jìn)入
_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:要開辟多少內(nèi)存
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;怎么去申請內(nèi)存
obj = (id)calloc(1, size);
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
// 3: 設(shè)置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);
}
根據(jù)源碼可得到alloc
流程圖:
alloc流程圖
1.計算開辟內(nèi)存大小
- 進(jìn)入
instanceSize
//編譯器快速計算內(nèi)存大小
size_t instanceSize(size_t extraBytes) const {
if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
return cache.fastInstanceSize(extraBytes);
}
// 計算類中所有屬性的大小 + 額外的字節(jié)數(shù)0
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
if (size < 16) size = 16;
return size;
}
通過斷點調(diào)試,發(fā)現(xiàn)進(jìn)入cache.fastInstanceSize
- 進(jìn)入
cache.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);
}
}
- 進(jìn)入
align16
//16字節(jié)對齊算法
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
內(nèi)存字節(jié)對齊
為什么要字節(jié)對齊:
- 通常內(nèi)存是由一個個字節(jié)組成的,
cpu
在存取數(shù)據(jù)時,并不是以字節(jié)為單位存儲,而是以塊為單位存取,塊的大小為內(nèi)存存取力度. 頻繁存取字節(jié)未對齊的數(shù)據(jù),會極大降低cpu的性能
,所以可以通過減少存取次數(shù)來降低cpu的開銷
- 16字節(jié)對齊,是由于在一個對象中,第一個屬性isa占8字節(jié),當(dāng)然一個對象肯定還有其他屬性,當(dāng)無屬性時,會預(yù)留8字節(jié),即16字節(jié)對齊,如果不預(yù)留,相當(dāng)于這個對象的isa和其他對象的isa緊挨著,容易造成訪問混亂
- 16字節(jié)對齊后,可以加快CPU讀取速度,同時使訪問更安全,不會產(chǎn)生訪問混亂的情況
字節(jié)對齊的原則, 參考這篇文章
-
開辟內(nèi)存大小流程圖:
開辟內(nèi)存大小流程圖.png
2. 申請空間,開辟內(nèi)存
obj = (id)calloc(1, size);
通過instanceSize計算的內(nèi)存大小,向內(nèi)存中申請大小
為size
的內(nèi)存,并賦值給obj
,因此obj
是指向內(nèi)存地址,并沒有與cls
關(guān)聯(lián)
3. 類與isa關(guān)聯(lián)
通過上面的幾步,得到了開辟好的內(nèi)存,這里需要把類與內(nèi)存地址關(guān)聯(lián)起來,得到一個對象isa
init分析
類方法init
// Replaced by CF (throws an NSException)
+ (id)init {
return (id)self;
}
init
是一個構(gòu)造方法 ,是通過工廠設(shè)計(工廠方法模式)
,主要是用于給用戶提供構(gòu)造方法入口.
實例方法init
- 進(jìn)入
init
- (id)init {
return _objc_rootInit(self);
}
- 進(jìn)入
_objc_rootInit
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;
}
小結(jié): 返回的是輸入的self
本身
new分析
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
小結(jié):
- 通過源碼可知
new
等于[alloc init]
- 開發(fā)過程中不建議用
new
,new
方法不會執(zhí)行重寫init
方法自定義的一些操作
下一篇: iOS底層探索002-內(nèi)存對齊