Getting the same memory address for NSStrings assigned from string literals

I get the same memory address for the code snippet below

NSString *str = @"2"; NSArray *arr = [NSArray arrayWithObjects:@"1", str, @"3", @"4", @"5", @"6", nil]; NSString *strTest = @"6"; strTest = @"2"; NSLog(@"object %x", [arr objectAtIndex:1]); 

The object "str", "strTest" and "log print" indicating the same address, although I declared a different instance for NSString , then how does this happen. Please let me know. It gets strange to me.

+4
source share
3 answers

str , and NSLog must indicate the same memory address, since it makes the same object and does not receive any new allocation. The two lines of the strTest variable strTest probably optimized by the compiler for one NSString *strTest = @"2" , and since NSString unchanged, there is no problem saving the memory space and pointing it to the same line @"2" that is allocated in the data segment of your executable file.

+5
source

There is no problem with this as they are string literals. You have two different addresses for str and strTest. They simply go to the same object, which is a string literal. You have NOT created two separate instances of them.

Try

 str = [NSString stringWithFormat:"%@", @"2"]; strTest = [NSSTring stringWithString:str]; 

or so. However, if you are still doing

 NSArray *arr = [NSArray arrayWithObjects:@"1", str, @"3", @"4", @"5", @"6", nil]; 

and then

 NSLog(@"object %x", [arr objectAtIndex:1]); 

you will see that the object with index 1 in arr and the object str refers to are the same way because they are there and they must be the same.

+4
source

String literals such as @ "2" are never issued, and they point to the same memory, which means that the pointer comparison is true and they have the same address.

+1
source

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


All Articles