【Coding】【5】iOS代码片段分析(一)alloc与init打印

本文最后更新于:2021年12月22日 上午

【Coding】系列目录


Code

1
2
3
4
5
6
7
8
9
Person *p = [Person alloc];
Person *p1 = [p init];
Person *p2 = [p init];
Person *p3 = [p1 init];

BYLog(@"%@---%p",p,&p);
BYLog(@"%@---%p",p1,&p1);
BYLog(@"%@---%p",p2,&p2);
BYLog(@"%@---%p",p3,&p3);

输出

截屏2021-01-07 下午8.54.03.png

分析

1
2
3
4
5
6
7
8
9
- (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方法会返回方法调用者

故所有指针都指向同一个地址,但是不同指针,其本身在内存中的地址不同,所以%@打印都相同,%p打印都不同。


联系方式

邮箱: adrenine@163.com