objective-cpointersdynamic-memory-allocation

Why a pointer to user-defined object does not hold the same address in the memory as the user-definded object itself


I am leaning blocks In objective-c, I wanted to understand the concept behind the pointers from the perspective of objective-c. given the code below, I expected that the the 3 statement to display the same result or at least the sam memory address. At least because, the pointer

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

The out put of the code are as follows:

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

Please let me know why the first value differs to the subsequent two values

code:

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

Solution

  • Every time you call alloc, new memory address allocates for the caller. init just initialized the already allocated memory, so the address won't change on init.

    You use alloc twice, so you get two memory addresses.