Reputation: 6940
I created three string, that bind it data with method argument. However, i face issue that all of three string share same memory, therefore, it show the same text. Here is how i create it:
-(void)buildViewsWIithTitle:(NSString*)eventTitle{
NSString *firstStr = @"";
NSString *secondStr = @"";
NSString *thirdStr = @"";
Next i set label text to all of this three string. I set it value like:
thirdStr = [NSString stringWithFormat:@"%@", eventTitle];
secondStr = [NSString stringWithFormat:@"%@", eventTitle]
firstStr = [NSString stringWithFormat:@"%@", eventTitle];
In console i output its memory just after creation:
NSLog(@"memory %p , %p , %p", firstStr, secondStr, thirdStr);
memory 0x109af82d8 , 0x109af82d8 , 0x109af82d8
Any idea how make memory address different for them?
Upvotes: 3
Views: 117
Reputation: 25692
As you are using NSString for all 3 objects, which can't be mutated, The compiler will check the value of the string, which is the same empty to all strings. The compiler will optimise the memory usage by pointing the same memory.
The iOS compiler optimizes references to string objects that have the same value (i.e., it reuses them rather than allocating identical string objects redundantly), so all three pointers are in fact pointing to same address.
If you used the NSMutableString, still it may point to the same object, but when you try to mutate the string, it will be copied to the new memory(Lazy memory allocation).
if you want the different memory for each string then you can allocate the memory then initialize the string, like
NSMutableString *str1 = [[NSMutableString alloc]initWithString:@""]
NSMutableString *str2 = [[NSMutableString alloc]initWithString:@""]
NSMutableString *str3 = [[NSMutableString alloc]initWithString:@""]
But note that NSMutableString is mutable.
Upvotes: 4
Reputation: 204
Maybe there's some kind of compiler optimisation going on. It determines (correctly) that the strings are the same so it optimises while compiling. As soon as you change your code so the strings will not be the same and recompile then the compiler won't optimise those particular strings.
thirdStr = [NSString stringWithFormat:@"a %@", eventTitle];
secondStr = [NSString stringWithFormat:@"b %@", eventTitle];
firstStr = [NSString stringWithFormat:@"c %@", eventTitle];
Upvotes: 1
Reputation: 27438
That's because your all string have address of [NSString stringWithFormat:@"%@", eventTitle];
and this is same for all strings.
For example if you will write below code in your viewdidload then you will get different memory address,
NSString *firstStr = @"";
NSString *secondStr = @"";
NSString *thirdStr = @"";
thirdStr = [NSString stringWithFormat:@"%@", @"eventTitle"];
secondStr = [NSString stringWithFormat:@"%@", @"eventTitle"];
firstStr = [NSString stringWithFormat:@"%@", @"eventTitle"];
NSLog(@"memory %p , %p , %p", firstStr, secondStr, thirdStr);
Because everystring has own memory and not pointing to any single string.
Upvotes: 1