Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting same memory address for NSStrings assigned from string literals

I'm getting same memory address for the below code snippet

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]);

Object "str", "strTest" and the "log print" giving same address though I've declared different instance for NSString then how is it happening. Please someone let me know. It is getting strange for me.

like image 260
Exploring Avatar asked Dec 27 '22 01:12

Exploring


1 Answers

str and the NSLog should provide the same memory address, since it's the same object and no new allocation is made. The two lines of the strTest variable are probably being optimized by the compiler to a single NSString *strTest = @"2", and since NSString is immutable there's no problem with saving the memory space and pointing it to the same @"2" string that is allocated in the data segment of your executable.

like image 116
StatusReport Avatar answered May 17 '23 19:05

StatusReport