一、对于 iOS 的底层原理探索,查找到函数所在的源码库,一般有以下方法实现:
二、作为 iOS 开发者,最需要关注的应该就是从应用启动到应用被 kill 掉这一整个生命周期的内容。不妨从最熟悉的 main 函数开始,一般来说,在 main.m 文件中打一个断点,左侧的调用堆栈视图应该如下图所示:
五、Apple 开源库源码
在 iOS 中,对象的属性需要进行内存对齐,而对象本身也需要进行内存对齐。内存对齐有三原则:
简而言之:
注意:
在Xocde中打印以下两个函数:
Boy *boy = [Boy alloc];
NSLog(@"%lu - %lu - %lu", sizeof(boy), class_getInstanceSize([Boy class]), malloc_size((__bridge const void *)(boy)));
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;
}
obj = (id)calloc(1, size);
size_t class_getInstanceSize(Class cls) {
if (!cls) return 0;
return cls->alignedInstanceSize();
}
C | OC | 32位 | 64位 |
---|---|---|---|
bool | BOOL(64位) | 1 | 1 |
signed char | (_signed char)int8_t、BOOL(32位) | 1 | 1 |
unsigned char | Boolean | 1 | 1 |
short | int16_t | 2 | 2 |
unsigned short | unichar | 2 | 2 |
int、int32_t | NSInteger(32位)、boolean_t(32位) | 4 | 4 |
unsigned int | NSUInteger(32位)、boolean_t(64位) | 4 | 4 |
long | NSInteger(64位) | 4 | 8 |
unsigned long | NSUInteger(64位) | 4 | 8 |
long long | int64_t | 8 | 8 |
float | CGFloat(32位) | 4 | 4 |
double | CGFloat(64位) | 8 | 8 |
运用Objective-C语言进行开发的时候,我们都知道可以通过 [XXX alloc]、[[XXX alloc] init]、[XXX new]的形式进行对象实例的创建,那么不禁会疑惑alloc、init、new它们各自都做了什么呢?同样的都是进行实例创建,它们之间有什么内在的关联呢?它们之间又有着什么样的区别呢?
Boy *boy1 = [Boy alloc];
Boy *boy2 = [boy1 init];
Boy *boy3 = [[Boy alloc] init];
Boy *boy4 = [Boy new];
NSLog(@"%@ %p %p",boy1, boy1, &boy1);
NSLog(@"%@ %p %p",boy2, boy2, &boy2);
NSLog(@"%@ %p %p",boy3, boy3, &boy3);
NSLog(@"%@ %p %p",boy4, boy4, &boy4);
打印结果
2020-09-02 00:32:43.295969+0800 iOS之alloc与init[1284:37780] <Boy: 0x6000008c03d0> 0x6000008c03d0 0x7ffee75284d8
2020-09-02 00:32:43.296121+0800 iOS之alloc与init[1284:37780] <Boy: 0x6000008c03d0> 0x6000008c03d0 0x7ffee75284d0
2020-09-02 00:32:43.296282+0800 iOS之alloc与init[1284:37780] <Boy: 0x6000008c03a0> 0x6000008c03a0 0x7ffee75284c8
2020-09-02 00:32:43.296370+0800 iOS之alloc与init[1284:37780] <Boy: 0x6000008c03c0> 0x6000008c03c0 0x7ffee75284c0
X0 X1..其中x0-x7八个寄存器是用来保存参数的
objc_msgSend会有两个默认参数,这也就意味着x0保存的是self,也就是isa指针,x1保存的是_cmd
register read x0 (register指令能够获取和修改各个寄存器的信息。)
po 0x4567899. “po”命令是“print object”(打印对象)的简写
既然是深入底层,那么肯定需要知道底层代码是做了什么事情,苹果是开源了这部分的代码,可以在Source Browser下载。下载下来的源码直接编译是通不过的,需要自己修改下配置,具体请参考objc_debug。
+ (id)alloc {
return _objc_rootAlloc(self);
}
id _objc_rootAlloc(Class cls) {
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false) {
#if __OBJC2__
// checkNil 为false,!cls 也为false ,所以slowpath 为 false,假值判断不会走到if里面,即不会返回nil
if (slowpath(checkNil && !cls)) return nil;
// 判断一个类是否有自定义的 +allocWithZone 实现,没有则走到if里面的实现
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));
}
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
bool hasDefaultAWZ( ) {
return data()->flags & RW_HAS_DEFAULT_AWZ;
}
#define RW_HAS_DEFAULT_AWZ (1<<16)
if (allocWithZone) return [cls allocWithZone:nil];
+ (id)allocWithZone:(struct _NSZone *)zone {
return _objc_rootAllocWithZone(self, (malloc_zone_t *)zone);
}
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone)
{
id obj;
#if __OBJC2__
// allocWithZone under __OBJC2__ ignores the zone parameter
(void)zone;
obj = class_createInstance(cls, 0);//创建对象
#else
if (!zone) {
obj = class_createInstance(cls, 0);
}
else {
obj = class_createInstanceFromZone(cls, 0, zone);
}
#endif
if (slowpath(!obj)) obj = callBadAllocHandler(cls);
return obj;
}
id class_createInstance(Class cls, size_t extraBytes) {
return _class_createInstanceFromZone(cls, extraBytes, nil);
}
tatic __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
//读取class的信息
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;
}
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.
// 如果size 小于 16,最小取16
if (size < 16) size = 16;
return size;
}
uint32_t alignedInstanceSize() {
return word_align(unalignedInstanceSize());
}
// May be unaligned depending on class's ivars.
// 读取当前的类的属性数据大小
uint32_t unalignedInstanceSize() {
assert(isRealized());
return data()->ro->instanceSize;
}
// 进行内存对齐
// WORD_MASK == 7
static inline uint32_t word_align(uint32_t x) {
return (x + WORD_MASK) & ~WORD_MASK;
}
if (fastpath(cls->canAllocFast())) {
// No ctors, raw isa, etc. Go straight to the metal.
bool dtor = cls->hasCxxDtor();
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
if (slowpath(!obj)) return callBadAllocHandler(cls);
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;
}
size_t fastInstanceSize(size_t extra) const
{
ASSERT(hasFastInstanceSize(extra));
//Gcc的内建函数 __builtin_constant_p 用于判断一个值是否为编译时常数,如果参数EXP 的值是常数,函数返回 1,否则返回 0
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
//删除由setFastInstanceSize添加的FAST_CACHE_ALLOC_DELTA16 8个字节
return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
}
}
// 16字节对齐算法
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
既然 alloc 创建了对象,那还要 init 干嘛呢?init 又做了什么呢?
- (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;
}
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}