【Code Analysis #1】iOS代码片段分析

1,260 阅读1分钟

Code

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

分析

- (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打印都不同。