Passing an Object to an Unallocated Pointer

Say I declared NSString like this

NSString *myString = [[NSString alloc] initWithString:@"Never Heard"];
NSString *tempString;

tempString = myString;

[myString release];

My question is, why does it work? As you can see, I did not set aside for tempString. Therefore, I do not think there is a need to release him. But if I try to allocate and initialize tempString, this will result in an error.

NSString *myString = [[NSString alloc] initWithString:@"Never Heard"];
NSString *tempString = [[NSString alloc] init];

tempString = myString;

[myString release];

I use NSString as an example, but instead I have different classes. I'm trying to emphasize how memory works here. Refine and explain?

+3
source share
3 answers

A pointer is just a memory address. You create only one object, and then point tempStringto that object. And tempString == myString.

[myString release] frees a string, leaving both pointers pointing to freed memory.

. - , . , .

+3

. , . :

tempString = myString;

tempString , myString. tempString myString.

+2
tempString = myString;

myString, tempString , "Never Hard". , .

, - "But if I try to alloc and init the tempString, it will bring an error."

1

- . tempString - . -

myString -> MemoryLocation_1 that has "Never Hard"
tempString -> MemoryLocation_2 and the location it is pointing to isn't intialized with any value.

Now, with this statement -
tempString = myString;

Both myString  and tempString -> MemoryLocation_1 that has "Never Hard"

MemoryLocation_2, . , . , . , .

+1

Source: https://habr.com/ru/post/1795946/


All Articles