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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With