首页 > 解决方案 > 为什么指向用户定义对象的指针在内存中与用户定义对象本身的地址不同

问题描述

我在学习objective-c,我想从objective-c的角度来理解指针背后的概念。鉴于下面的代码,我希望 3 语句显示相同的结果或至少显示 sam 内存地址。至少因为,指针

meAsImpl refers/points/observs the memory location of the user-defined object MeAsImpl
Hence, the 3 NSLog statement should display the same results

代码的输出如下:

 <MeAsImpl: 0x600000194120>
<MeAsImpl: 0x60000019f240>
<MeAsImpl: 0x60000019f240>

请让我知道为什么第一个值与后面的两个值不同

代码

    MeAsImpl *meAsImpl = [[MeAsImpl alloc] init];
    NSLog(@"%@", meAsImpl);
    NSLog(@"%@", MeAsImpl.alloc);
    NSLog(@"%@", MeAsImpl.alloc.init);

标签: objective-cpointersdynamic-memory-allocation

解决方案


每次调用时,都会alloc为调用者分配新的内存地址。init刚刚初始化了已经分配的内存,所以地址不会改变init

你使用alloc两次,你得到两个内存地址。


推荐阅读